Title here
Summary here
Functions are central in Java. We’ll learn about functions (known as methods in Java) with a few different examples.
public class Functions {
// Here's a method that takes two ints and returns
// their sum as an int.
public static int plus(int a, int b) {
// Java requires explicit returns, i.e. it won't
// automatically return the value of the last
// expression.
return a + b;
}
// In Java, we can't omit parameter types even if they're the same.
// Each parameter must have its type declared.
public static int plusPlus(int a, int b, int c) {
return a + b + c;
}
public static void main(String[] args) {
// Call a method just as you'd expect, with
// name(args).
int res = plus(1, 2);
System.out.println("1+2 = " + res);
res = plusPlus(1, 2, 3);
System.out.println("1+2+3 = " + res);
}
}To run this program:
$ javac Functions.java
$ java Functions
1+2 = 3
1+2+3 = 6There are several other features to Java methods. One is method overloading, which allows multiple methods with the same name but different parameters, which we’ll look at next.
Comments powered by Disqus