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 loop through an array in Java?

You can use an enhanced for loop, also called a for-each loop, to read each element in an array.

In this example, you will loop through an array of programming language names and print each name.

Source code

public class ArrayLoopExample {
    void main() {
        String[] languages = {"Java", "Python", "JavaScript"};

        for (String language : languages) {
            IO.println(language);
        }

        IO.println("Total languages: " + languages.length);
    }
}

Explanation

The following statement creates an array containing three strings:

String[] languages = {"Java", "Python", "JavaScript"};

String[] means that the variable holds an array of strings. Each value inside the braces is an element of the array.

The enhanced for loop reads the elements in their array order:

for (String language : languages) {
    IO.println(language);
}

On each iteration, language holds the next element:

Iteration Value of language
1 "Java"
2 "Python"
3 "JavaScript"

The loop ends after processing the last element. You do not need to manage an index or write a condition to stop the loop.

Finally, the program prints the number of elements using the array’s length field:

IO.println("Total languages: " + languages.length);

Use length without parentheses when working with arrays.

Run the example

Compile and run the file:

javac ArrayLoopExample.java
java ArrayLoopExample

Output

Java
Python
JavaScript
Total languages: 3

Use an enhanced for loop when you need to read each element. If you need the position of an element or want to replace values in the array, use an index-based for loop.

How do I convert arrays to lists and vice versa in Kotlin?

In Kotlin, you can convert arrays to lists and lists to arrays using standard library functions.

Array to List

Use toList():

val array = arrayOf("a", "b", "c")

val list: List<String> = array.toList()

println(list) // [a, b, c]

If you want a mutable list, use toMutableList():

val array = arrayOf("a", "b", "c")

val mutableList: MutableList<String> = array.toMutableList()

mutableList.add("d")

println(mutableList) // [a, b, c, d]

List to Array

Use toTypedArray():

val list = listOf("a", "b", "c")

val array: Array<String> = list.toTypedArray()

println(array.contentToString()) // [a, b, c]

Primitive Arrays

Kotlin has special primitive array types like IntArray, DoubleArray, and BooleanArray.

IntArray to List

val intArray = intArrayOf(1, 2, 3)

val list: List<Int> = intArray.toList()

println(list) // [1, 2, 3]

List<Int> to IntArray

Use toIntArray():

val list = listOf(1, 2, 3)

val intArray: IntArray = list.toIntArray()

println(intArray.contentToString()) // [1, 2, 3]

Other primitive conversions work similarly:

val doubles: List<Double> = listOf(1.1, 2.2, 3.3)
val doubleArray: DoubleArray = doubles.toDoubleArray()

val booleans: List<Boolean> = listOf(true, false)
val booleanArray: BooleanArray = booleans.toBooleanArray()

Important Note: asList()

For object arrays, you can also use asList():

val array = arrayOf("a", "b", "c")

val list = array.asList()

The difference is:

val array = arrayOf("a", "b", "c")

val copiedList = array.toList()
val backedList = array.asList()
  • toList() creates a new list copy.
  • asList() returns a list backed by the original array.

Example:

val array = arrayOf("a", "b", "c")
val list = array.asList()

array[0] = "z"

println(list) // [z, b, c]

So in most cases, use:

array.toList()
list.toTypedArray()

And for primitive types:

intArray.toList()
list.toIntArray()

Why do I get ArrayIndexOutOfBoundsException in Java?

The ArrayIndexOutOfBoundsException exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Array with 10 elements

For example see the code snippet below:

String[] vowels = new String[]{"a", "i", "u", "e", "o"}
String vowel = vowels[10]; // throws the ArrayIndexOutOfBoundsException

Above we create a vowels array with five elements. This will make the array have indexes between 0..4. On the next line we tried to access the tenth element of the array which is illegal. This statement will cause the ArrayIndexOutOfBoundsException thrown.

We must understand that arrays in Java are zero indexed. The first element of the array will be at index 0 and the last element will be at index array-size - 1. So be careful with your array indexes when accessing array elements. For example if you have an array with 5 elements this mean that the index of the array is from 0 to 4.

If you are trying to iterate an array using for loop. Make sure the index start from 0 and execute the loop while the index is less than the length of the array, you can get the length of the array using the array length property. Let’s see the code snippet below:

for (int i = 0; i < vowels.length; i++) {
    String vowel = vowels[i];
    System.out.println("vowel = " + vowel);
}

Or if you don’t need the index you can simplify your code using the for-each or enhanced for-loop statement instead of the classic for loop statement as shown below:

for (String vowel : vowels) {
    System.out.println("vowel = " + vowel);
}