Functions in Java

Functions are central in Java. We’ll learn about functions (called 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 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 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 the program:

$ javac Functions.java
$ java Functions
1+2 = 3
1+2+3 = 6

There are several other features to Java methods. One is method overloading, which allows multiple methods with the same name but different parameter lists. We’ll look at this in future examples.

[Next example: Method Overloading]