Title here
Summary here
Functions are central in Java. We’ll learn about functions with a few different examples.
public class Functions {
// Here's a function 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 the type for parameters, even if they're
// of the same type. Each parameter needs 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 function 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 the program, compile it and then use java
to execute:
$ javac Functions.java
$ java Functions
1+2 = 3
1+2+3 = 6
There are several other features to Java methods (functions). One is method overloading, which allows multiple methods to have the same name with different parameters.