How to initialize an array in java

An array can be initialized in java like the following:

Syntax:

int[] tab = {1,2,3};

Example:

This example shows a first method creating an array and initializes it with 3 integers. The values are 1, 2 and 3. The values are then written in the output.
The the second method an array can be initialized, is by creating the array object and then assigning values to the different indexes of the array. This example creates an object called tab2 and assigns a value to each index. All the values are then written in the output.

public class ArraysTest {

 
    public static void main(String[] argv) {

	int[] tab = {1,2,3};

	System.out.println( "Tab1:" );
	
	// Loop on all the values of tab1
	for(int c : tab){
	    System.out.println( c );
	}

	int[] tab2 = new int[3];
	tab2[0] = 0;
	tab2[1] = 1;
	tab2[2] = 2;

	System.out.println( "Tab2:" );

	// Loop on all the values of tab2
	for(int c : tab){
	    System.out.println( c );
	}
	
    }

}

The output will be:

Tab1:
1
2
3
Tab2:
1
2
3

The values in the output are the same for both tabs; this is showing that the two methods are equivalent.

References:

Java Arrays

Recent Comments