Introduction to Java: Arrays

Introduction to Java: Arrays


Arrays are a collection of elements having same type. To declare an array, we define the variable type with square brackets.

Example:


public class FirstArrayExample {
    public static void main(String[] args) {
        int[] num = new int[3];

        num[0] = 1;
        num[1] = 2;
        num[2] = 3;

        for (int i = 0; i < num.length; i++) {
            System.out.println(num[i]);
        }
    }
}


Output:


$ javac FirstArrayExample.java
$ java FirstArrayExample
1
2
3


We can use a shorter and simpler syntax to initialize an array, and we use curly brackets and specify the elements within these brackets.

Example:


public class SecondArrayExample {
    public static void main(String[] args) {
        String[] names = {"Java", "Go", "Kotlin"};

        for (String name : names) {
            System.out.println(name);
        }
    }
}


In this example we created an array of string values and used the forEach loop to output all elements.

Output:


$ javac SecondArrayExample.java
$ java SecondArrayExample
Java
Go
Kotlin


Array Length
We use the length property to find out how many elements an array has.

Example:


public class ArrayLengthExample {
    public static void main(String[] args) {
        int[] numbers = { 10, 1, 3, 4, 5, 6 };

        int totalNumbers = numbers.length;

        System.out.println("Total numbers: " + totalNumbers);
    }
}


Output:


$ javac ArrayLengthExample.java
$ Java ArrayLengthExample
Total numbers: 6


Multidimensional Arrays
Java programming language allows multidimensional Arrays, in other words array of arrays.

Example:


public class MultidimensionalArrays {
    public static void main(String[] args) {
        int[][] multiArrayNum = { { 1, 2, 3 }, { 4, 5, 6 } };

        System.out.println(multiArrayNum[0][2]);
    }
}


Output:


$ javac MultidimensionalArrays.java
$ java MultidimensionalArrays
3


We use for-loop inside another for-loop to iterate over multidimensional arrays.

Example:


public class MultidimensionalArraysForLoopExample {
    public static void main(String[] args) {
        int[][] numbers = { { 1, 2, 3 }, { 4, 5, 6 } };

        for (int i = 0; i < numbers.length; i++) {
            for (int j = 0; j < numbers[i].length; j++) {
                System.out.println(numbers[i][j]);
            }
        }
    }
}


Output:


$ javac MultidimensionalArraysForLoopExample.java
$ java MultidimensionalArraysForLoopExample
1
2
3
4
5
6


Share this: