How do I pass a variable number of arguments to a method in Java?

You can use varargs to let a method accept any number of arguments of the same type. Declare a varargs parameter by adding three dots (...) after its type.

In this example, you will create a method that adds integers. You can call it with two numbers, several numbers, or no numbers.

Source code

public class VarargsExample {
    void main() {
        IO.println("Sum of two numbers: " + sum(10, 20));
        IO.println("Sum of four numbers: " + sum(5, 10, 15, 20));
        IO.println("Sum with no arguments: " + sum());

        int[] numbers = {3, 6, 9};
        IO.println("Sum of array elements: " + sum(numbers));
    }

    int sum(int... numbers) {
        int total = 0;

        for (int number : numbers) {
            total += number;
        }

        return total;
    }
}

Explanation

The sum() method declares a varargs parameter:

int sum(int... numbers) {

The declaration int... numbers lets callers pass zero or more int values. Inside the method, numbers is an int[] array.

For example, this call passes two values:

sum(10, 20)

Inside the method, numbers contains 10 and 20.

The method starts with a total of zero, then adds each element:

int total = 0;

for (int number : numbers) {
    total += number;
}

The statement total += number adds the current number to total. After the loop finishes, the method returns the total.

When you call the method without arguments:

sum()

Java supplies an empty array. The loop has no elements to process, so the method returns 0.

You can also pass an existing array directly:

int[] numbers = {3, 6, 9};
sum(numbers);

The method reads the array elements and returns 18.

Run the example

Compile and run the file:

javac VarargsExample.java
java VarargsExample

Output

Sum of two numbers: 30
Sum of four numbers: 50
Sum with no arguments: 0
Sum of array elements: 18

Rules to remember

A method can have only one varargs parameter, and it must be the last parameter.

For example, this declaration is valid:

int sum(String label, int... numbers)

This declaration is invalid because another parameter appears after the varargs parameter:

int sum(int... numbers, String label)

Use varargs when callers should be able to supply different numbers of values without creating an array explicitly.

How do I overload a method in Java?

Method overloading lets you define multiple methods with the same name but different parameter lists. You can use it to perform a similar task with different inputs.

In this example, you will create three add() methods to add two integers, three integers, or two floating-point numbers.

Source code

public class MethodOverloadingExample {
    void main() {
        int twoIntegerSum = add(10, 20);
        int threeIntegerSum = add(10, 20, 30);
        double twoDoubleSum = add(2.5, 3.75);

        IO.println("Sum of two integers: " + twoIntegerSum);
        IO.println("Sum of three integers: " + threeIntegerSum);
        IO.println("Sum of two doubles: " + twoDoubleSum);
    }

    int add(int first, int second) {
        return first + second;
    }

    int add(int first, int second, int third) {
        return first + second + third;
    }

    double add(double first, double second) {
        return first + second;
    }
}

Explanation

All three methods are named add(), but their parameter lists differ:

Method Parameters
add(int first, int second) Two integers
add(int first, int second, int third) Three integers
add(double first, double second) Two doubles

When you call an overloaded method, the compiler selects the applicable version based on the number and types of the arguments.

The following call passes two int values:

int twoIntegerSum = add(10, 20);

It selects add(int, int) and returns 30.

This call passes three int values:

int threeIntegerSum = add(10, 20, 30);

It selects add(int, int, int) and returns 60.

Finally, this call passes two double values:

double twoDoubleSum = add(2.5, 3.75);

It selects add(double, double) and returns 6.25.

Run the example

Compile and run the file:

javac MethodOverloadingExample.java
java MethodOverloadingExample

Output

Sum of two integers: 30
Sum of three integers: 60
Sum of two doubles: 6.25

Rules to remember

Overloaded methods must differ in the number, types, or order of their parameter types.

Changing only the parameter names does not create a different overload. Changing only the return type is also insufficient. For example, these two declarations cannot appear together in the same class:

int add(int first, int second) {
    return first + second;
}

double add(int first, int second) {
    return first + second;
}

Both methods have the same name and parameter types, so the compiler reports an error.

How do I create a method that returns a value in Java?

A method can perform a task and return a result to the code that calls it. You can store that result in a variable or use it in another expression.

In this example, you will create a method that adds two integers and returns their sum.

Source code

public class ReturnValueExample {
    void main() {
        int firstNumber = 12;
        int secondNumber = 8;

        int result = add(firstNumber, secondNumber);

        IO.println("First number: " + firstNumber);
        IO.println("Second number: " + secondNumber);
        IO.println("Sum: " + result);
    }

    int add(int first, int second) {
        return first + second;
    }
}

Explanation

The add() method accepts two integers and returns an integer:

int add(int first, int second) {
    return first + second;
}

Each part of the declaration has a purpose:

Part Purpose
int before add Specifies the type of value the method returns
add Names the method
int first, int second Declares the parameters that receive the input values
return first + second; Adds the values and returns the result

The return statement ends the current method call and sends a value back to the caller.

Inside main(), the following statement calls the method:

int result = add(firstNumber, secondNumber);

The values of firstNumber and secondNumber are passed as arguments. Inside add(), the parameters first and second receive those values.

The method calculates 12 + 8 and returns 20. That value is then assigned to result.

Both main() and add() are instance methods in this example. Java 25 supports an instance main() method, so you can call add() directly without making either method static.

Run the example

Compile and run the file:

javac ReturnValueExample.java
java ReturnValueExample

Output

First number: 12
Second number: 8
Sum: 20

Returning a value versus printing it

The add() method returns its result without printing it. The calling code decides what to do with that value.

For example, you can use the returned value in another calculation:

int doubledSum = add(12, 8) * 2;

Here, add(12, 8) returns 20, which is multiplied by two. The value of doubledSum becomes 40.

Use a return type such as int when a method needs to provide a result. Use void when the method does not return a value.

How do I loop through a two-dimensional array in Java?

You can use nested enhanced for loops to read every element in a two-dimensional array. The outer loop reads each row, and the inner loop reads the values in that row.

In this example, you will print a grid of integers, with each row on a separate line.

Source code

public class TwoDimensionalArrayExample {
    void main() {
        int[][] numbers = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        for (int[] row : numbers) {
            String separator = "";

            for (int number : row) {
                IO.print(separator + number);
                separator = " ";
            }

            IO.println();
        }
    }
}

Explanation

The following declaration creates a two-dimensional array:

int[][] numbers = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

In Java, a two-dimensional array is an array whose elements are arrays. Here, numbers contains three rows, and each row contains three integers.

The outer loop reads one row at a time:

for (int[] row : numbers) {

The variable row has the type int[] because each row is an array of integers.

Inside the outer loop, the inner loop reads each number in the current row:

for (int number : row) {
    IO.print(separator + number);
    separator = " ";
}

IO.print() writes output without starting a new line.

The separator variable starts as an empty string for each row. After printing the first number, it becomes a space. This places spaces between the numbers without adding a trailing space.

After the inner loop finishes, the following statement starts a new line:

IO.println();

The outer loop then moves to the next row.

Run the example

Compile and run the file:

javac TwoDimensionalArrayExample.java
java TwoDimensionalArrayExample

Output

1 2 3
4 5 6
7 8 9

Rows with different lengths

The same loop also works when rows contain different numbers of elements. For example, replace the array declaration with:

int[][] numbers = {
        {1, 2},
        {3, 4, 5},
        {6}
};

The output becomes:

1 2
3 4 5
6

Each inner loop processes the elements in its current row, so the rows do not need to have the same length.

How do I find the largest number in an array in Java?

You can find the largest number in an array by looping through its elements and keeping track of the largest value found so far.

In this example, you will compare integers in an array and print the largest number.

Source code

public class LargestNumberExample {
    void main() {
        int[] numbers = {12, -5, 38, 7, 24};

        if (numbers.length == 0) {
            IO.println("The array is empty.");
            return;
        }

        int largest = numbers[0];

        for (int index = 1; index < numbers.length; index++) {
            if (numbers[index] > largest) {
                largest = numbers[index];
            }
        }

        IO.println("Largest number: " + largest);
    }
}

Explanation

The following statement creates an array of integers:

int[] numbers = {12, -5, 38, 7, 24};

Before accessing an element, the program checks whether the array is empty:

if (numbers.length == 0) {
    IO.println("The array is empty.");
    return;
}

An empty array has no largest value. The return statement ends the main() method so the program does not try to access an element that does not exist.

Next, the program uses the first element as the initial largest value:

int largest = numbers[0];

Array indexes start at zero, so numbers[0] refers to the first element.

Starting with an actual element makes the calculation work even when every number in the array is negative. Starting with 0 would give an incorrect result in that case.

The loop begins at index 1 because the first element is already stored in largest:

for (int index = 1; index < numbers.length; index++) {
    if (numbers[index] > largest) {
        largest = numbers[index];
    }
}

On each iteration, the program compares the current element with largest. If the element is greater, it becomes the new largest value.

For this array, the comparisons work as follows:

Current element Largest value after comparison
-5 12
38 38
7 38
24 38

After the loop finishes, largest contains 38.

Run the example

Compile and run the file:

javac LargestNumberExample.java
java LargestNumberExample

Output

Largest number: 38

If you change the array to contain only negative numbers:

int[] numbers = {-12, -5, -38, -7, -24};

The output becomes:

Largest number: -5