Skip to content

August 7, 2014

Define an Array in Java and Iterate Through It

by admin

Here is how to define an array or a multi-dimensional array in Java and how to iterate through it:

package learn_java;
 
public class Learn_java {
 
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
 
        for (int i=0;i< array1.length; i++ ) {
            System.out.print(array1[i] + " ");
        }
 
        System.out.println("\n");
 
        int[][] array2 = { {1,2,3}, {4,5,6}, {7,8,9} };
 
        for (int i=0; i < array2.length; i++ ) {
            for (int j=0; j < array2[i].length; j++ ) {
                System.out.print(array2[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Or in order to iterate through the array using enhanced for loop you can use:

package learn_java;
 
public class Learn_java {
 
    public static void main(String[] args) {
        int[] array1 = {1, 2, 3, 4, 5};
 
        for (int number : array1) {
            System.out.print(number + " ");
        }
 
        System.out.println("\n");
 
        int[][] array2 = { {1,2,3}, {4,5,6}, {7,8,9} };
 
        for (int[] subArray1 : array2) {
            for (int number : subArray1) {
                System.out.print(number + " ");
            }
            System.out.println();
        }   
    }
}
Read more from Java Examples

Leave a Reply

required
required

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments