Thursday, June 27, 2013

Using anonymous array to initialize an array in JAVA

There was a mistake when I'm declaring an array of integer first, and attempt to initialize it later will get a compiler error. The following code is what I'm trying to describe.

int[] theArray;
theArray = {1, 2};

It has to be either do it in this way:

int[] theArray = {1, 2};  // (1)

or this way:

int[] theArray;
theArray = new int[] (1, 2);  // (2)

In (1), theArray is an initializer block used to create and initialize the elements. In (2), an anonymous array expression is used.

No comments: