Date: 2011mar30
Update: 2025oct21
Language: Java
Keywords: init
Q. Java: How to initialize an array
A. Full example:
import java.util.Arrays;
class Demo {
// I do it this way:
static int[] myArray1 = { 1, 2, 3 };
// which is nice and compact.
// Some books tell you to do:
static int[] myArray2 = new int[] { 1, 2, 3 };
// which works but is more verbose.
// Initialize a 2D array in this way:
static int[][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9} };
public static final void main(String []args) {
System.out.println("myArray1=" + Arrays.toString(myArray1));
System.out.println("myArray2=" + Arrays.toString(myArray2));
System.out.println("twoDimArray=" + Arrays.toString(twoDimArray));
}
}
Output:
myArray1=[1, 2, 3]
myArray2=[1, 2, 3]
twoDimArray=[[I@971d0d8, [I@51931956, [I@2b4a2ec7]