Array syntax

Declare Array

The following syntax is used to declare an array variable. In the syntax, the keyword Type stands for the data type of the values used and the brackets [] indicate that it is an array variable.

Instantiation creates an instance of the same data type and is performed with the new operator in Java.

The data type must be the same on both sides. In the square brackets you must specify the desired number of elements to be stored in the array variable.

Type[] name = new Type[Number];
Type name[] = new Type[Number];

Initialize Array

An array can be declared, instantiated and initialized in a one-line syntax. The following syntax references can be used in this context.

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

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

        // shorthand
        for (int i : myArray) {
            System.out.println(i);
        }
    }
}
Output
1
2
3
4
public class ArrayBasics {
	public static void main(String[] args) {
		int[] myArray = {1, 2, 3, 4};

		System.out.println(myArray[0]);
		System.out.println(myArray[1]);
		System.out.println(myArray[2]);
		System.out.println(myArray[3]);
	}
}
Output
1
2
3
4