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.

How do I print a heart pattern using loops in Java?

You can print a filled heart by visiting points on a grid and checking whether each point belongs to a heart-shaped region. Nested for loops produce the rows and columns, while a mathematical condition selects the positions that contain stars.

Source code

Save this example as HeartPatternExample.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.

void main() {
    int rows = 20;
    int columns = 40;

    for (int row = 0; row <= rows; row++) {
        double y = 1.5 - 3.0 * row / rows;

        for (int column = 0; column <= columns; column++) {
            double x = -1.5 + 3.0 * column / columns;
            double a = x * x + y * y - 1;

            if (a * a * a - x * x * y * y * y <= 0) {
                IO.print("*");
            } else {
                IO.print(" ");
            }
        }
        IO.println();
    }
}

Explanation

The pattern uses the heart-shaped region defined by this inequality:

(x² + y² - 1)³ - x²y³ <= 0

You do not need to derive the formula to practice the loops. Treat it as a membership test: a point that satisfies the condition gets a star; any other point gets a space. Unlike a circle, this region has two rounded lobes at the top and a point at the bottom.

The outer loop selects the row and calculates its vertical coordinate, y. It starts at 1.5 and moves downward to -1.5. Console output grows downward, so decreasing y keeps the heart upright.

The inner loop visits each column and calculates its horizontal coordinate, x, from -1.5 to 1.5. The constants 3.0 represent the width and height of this coordinate range. Using 3.0 makes the arithmetic floating-point rather than integer division, allowing neighboring positions to have fractional coordinates.

The variables rows and columns specify the number of intervals across the coordinate range. Because both loops include their final index with <=, the program prints rows + 1 lines with columns + 1 character positions per line. The example therefore samples a grid of 21 rows and 41 columns.

For each position, a stores x * x + y * y - 1. The condition then multiplies the values to calculate the powers in the inequality. In Java, ^ is an exclusive-OR operator, not exponentiation, so it would not express these powers.

IO.print("*") and IO.print(" ") each occupy one character position. After the inner loop finishes, IO.println() starts the next row. The IO class belongs to java.lang, so no explicit import is needed.

There are about twice as many horizontal intervals as vertical intervals. This helps balance the proportions in terminal fonts whose characters are taller than they are wide. The result remains a stepped approximation, and its appearance depends on the font. Rows outside the heart contain only spaces and appear blank.

Run the example

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

java HeartPatternExample.java

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

javac HeartPatternExample.java
java HeartPatternExample

Output

           ******       ******
        ************ ************
      *****************************
      *****************************
     *******************************
     *******************************
      *****************************
      *****************************
       ***************************
        *************************
          *********************
            *****************
              *************
                *********
                   ***

Display the output in a monospaced font to preserve alignment. Trailing spaces are omitted from the output shown here; leading spaces and blank rows are preserved.

Try it yourself

Change rows to 30 and columns to 60. The coordinate range stays the same, but the denser grid gives the heart more detail. Keep both values positive to sample the full range correctly.

Replace IO.print("*") with IO.print("#") to change the drawing character without changing the shape.

Finally, change the condition to x * x + y * y <= 1. The same loops now draw a filled circle in the sampled coordinate range. Compare this coordinate-based approach with How do I print a circle pattern using loops in Java?.