Java Tutorial · Methods · Lesson 17 of 37

Java Methods

Define methods with parameters and return values, and overload them.

Defining a method

A method is a named block of code inside a class. Its signature lists the return type, name and parameters:

Example 1
public class Main {
    public static void main(String[] args) {
        greet("Ada");
        int sum = add(3, 4);
        System.out.println("Sum: " + sum);
        System.out.println("Is 7 even? " + isEven(7));
    }

    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    static int add(int a, int b) {
        return a + b;
    }

    static boolean isEven(int n) {
        return n % 2 == 0;
    }
}

Output

Hello, Ada!
Sum: 7
Is 7 even? false

Run this on your computer — see “Get Started” for setup.

  • static methods belong to the class and can be called from main directly.
  • void means the method returns nothing.
  • Java passes arguments by value — for objects, the value is a reference, so a method can change an object's contents but not replace the caller's variable.

Overloading

Several methods can share a name if their parameter lists differ:

Example 2
public class Main {
    public static void main(String[] args) {
        System.out.println(area(5));
        System.out.println(area(3, 4));
        System.out.println(area(2.5));
    }

    static int area(int side) {
        return side * side;
    }

    static int area(int width, int height) {
        return width * height;
    }

    static double area(double radius) {
        return Math.round(Math.PI * radius * radius * 100) / 100.0;
    }
}

Output

25
12
19.63

Run this on your computer — see “Get Started” for setup.

Varargs

int... numbers accepts any number of arguments as an array:

Example 3
public class Main {
    public static void main(String[] args) {
        System.out.println(sum());
        System.out.println(sum(1, 2, 3));
        System.out.println(sum(new int[]{10, 20}));
    }

    static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) total += n;
        return total;
    }
}

Output

0
6
30

Run this on your computer — see “Get Started” for setup.

Test yourself

What return type does a method that returns nothing have?

  1. null
  2. void
  3. none
  4. empty
Show answer

Answer: void