Skip to content
On this page

Traverse Array

We introduced the data type of array in Java Programming Basics. With the array, we still need to operate on it. One of the most common operations on arrays is traversal.

The array can be traversed through for loop. Because each element of the array can be accessed by index, an array traversal can be completed using a standard for loop:

java
public class Main {
  public static void main(String[] args) {
    int[] ns = { 1, 4, 9, 16, 25 };
    for (int i=0; i<ns.length; i++) {
      int n = ns[i];
      System.out.println(n);
    }
  }
}

In order to implement for loop traversal, the initial condition is i=0 , because the index always starts from 0 , and the condition for continuing the loop is i<ns.length , because when i=ns.length , i has exceeded the index range (index range is 0 ~ ns.length-1 ), after each loop, i++ .

The second way is to use a for each loop to directly iterate each element of the array:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        for (int n : ns) {
            System.out.println(n);
        }
    }
}

Note: In the for (int n : ns) loop, the variable n directly gets the elements of the ns array, not the index.

Obviously for each loop is more concise. However, the for each loop cannot get the index of the array, so which type of for loop to use depends on our needs.

Directly print the array variable and get the reference address of the array in the JVM:

java
int[] ns = { 1, 1, 2, 3, 5, 8 };
System.out.println(ns); // similar [I@7852e922

This doesn't make sense since we want to print the element contents of the array. So, use for each loop to print it:

java
int[] ns = { 1, 1, 2, 3, 5, 8 };
for (int n : ns) {
    System.out.print(n + ", ");
}

Printing using for each loop is also cumbersome. Fortunately, the Java standard library provides Arrays.toString() , which can quickly print array contents:

java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 1, 2, 3, 5, 8 };
        System.out.println(Arrays.toString(ns));
    }
}

Practise

Please iterate through the array in reverse order and print each element:

java
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        // Print array elements in reverse order:
        for (???) {
            System.out.println(???);
        }
    }
}

Summary

You can use a for loop to traverse an array. The for loop can access the array index. for each loop directly iterates each array element, but cannot obtain the index;

Use Arrays.toString() to quickly obtain array contents.

Traverse Array has loaded