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

How do I print a number spiral using loops in Java?

You can create a clockwise number spiral by filling a two-dimensional array one layer at a time. Start at the top-left corner, move right, down, left, and up, then repeat inside the remaining area. After filling the array, print its rows in order.

Source code

Save this example as NumberSpiralExample.java. It uses a Java 25 compact source file with void main() and the IO console methods. Use JDK 25 or later; no preview flags or external libraries are required. This example introduces arrays and a while loop alongside the for loops used in earlier patterns.

void main() {
    int size = 5;
    int[][] spiral = new int[size][size];
    int top = 0;
    int bottom = size - 1;
    int left = 0;
    int right = size - 1;
    int number = 1;

    while (top <= bottom && left <= right) {
        for (int column = left; column <= right; column++) {
            spiral[top][column] = number++;
        }
        top++;

        for (int row = top; row <= bottom; row++) {
            spiral[row][right] = number++;
        }
        right--;

        if (top <= bottom) {
            for (int column = right; column >= left; column--) {
                spiral[bottom][column] = number++;
            }
            bottom--;
        }

        if (left <= right) {
            for (int row = bottom; row >= top; row--) {
                spiral[row][left] = number++;
            }
            left++;
        }
    }

    int width = String.valueOf(size * size).length();
    for (int row = 0; row < size; row++) {
        for (int column = 0; column < size; column++) {
            if (column > 0) {
                IO.print(" ");
            }
            String value = String.valueOf(spiral[row][column]);
            for (int space = value.length(); space < width; space++) {
                IO.print(" ");
            }
            IO.print(value);
        }
        IO.println();
    }
}

Explanation

The declaration int[][] spiral = new int[size][size] creates a square array. Access each position with spiral[row][column]. A size of five gives 25 positions, which the program fills with the integers 1 through 25.

Four variables describe the unfilled area:

Variable Initial value for size 5 Meaning
top 0 First unfilled row
bottom 4 Last unfilled row
left 0 First unfilled column
right 4 Last unfilled column

The while loop continues as long as the top boundary has not passed the bottom boundary and the left boundary has not passed the right boundary. The logical AND operator, &&, requires both comparisons to be true.

Each iteration fills the available edges in clockwise order:

  1. Fill the top row from left to right, then increase top.
  2. Fill the right column from top to bottom, then decrease right.
  3. If a row remains, fill the bottom row from right to left, then decrease bottom.
  4. If a column remains, fill the left column from bottom to top, then increase left.

Updating each boundary before moving to the next edge prevents corners from being filled twice. The two if statements check whether the corresponding boundaries still permit another edge. This matters near the center, where the remaining area may be only one row or one column. The for loop conditions also prevent traversal when their ranges are empty.

The expression number++ uses the current value for the assignment and then increases it by one. For example, spiral[0][0] = number++ stores 1 and leaves number equal to 2.

After the outer layer is complete, the boundaries enclose a smaller area. The next iteration fills that layer, continuing until the array is full. For an odd size, the last layer is a single center position; for an even size, it is a two-by-two layer.

Aligning the output

The array is filled in spiral order but printed in ordinary row order. The two output loops visit every row and column from index zero onward.

String.valueOf(size * size).length() calculates the number of digits in the largest value. For this example, the largest value is 25, so the field width is two characters. A one-digit value receives one leading space, while a two-digit value receives none.

The program also prints one separator space before every column except the first. This keeps the columns readable without adding a separator after the last value. IO.println() ends each row. The IO class belongs to java.lang, so no explicit import is needed.

Run the example

With JDK 25 or later installed, open a terminal in the directory containing the source file and run it directly:

java NumberSpiralExample.java

You can also compile the source file explicitly and then run the compiled program:

javac NumberSpiralExample.java
java NumberSpiralExample

Output

 1  2  3  4  5
16 17 18 19  6
15 24 25 20  7
14 23 22 21  8
13 12 11 10  9

Display the output in a monospaced font to preserve column alignment.

Try it yourself

Change size to 4. Trace how the four boundaries move after filling the outer layer, then check the two-by-two inner layer. Compare this with the single center position for size = 5.

Try size = 1, which prints only 1. A size of zero creates an empty array and prints no rows. A negative size causes NegativeArraySizeException when the array is created. Use small positive sizes, such as 3 through 10, for this exercise.

Finally, replace number++ with the constant 1 in all four filling loops. Observe that every position is filled once, even though the traversal changes direction at each edge.