简体   繁体   中英

What is the difference between these two statements in Java?

int[] X = {1,2,3}; 
int[] Y = new int[] {1,2,3}

Will the content of array X also be stored on heap?

The only difference is that the first statement works only when the array variable is declared, while the second can be written separately from the declaration :

int[] X;
int[] Y;
X = {1,2,3}; // doesn't work
Y = new int[] {1,2,3}; // works

These two statements are technically grammatically different but have identical effects.

An array initializer can appear as part of a local variable declaration initializer as in:

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

and also an array creation expression as in:

new int[] {1,2,3}

And yes, X will be on the heap. All objects in Java are on the heap and since arrays are objects, all arrays are on the heap.

Java provides a ease of initializing arrays. So with out new operator you can directly assign value. Like

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

Here the size of array is know by no.of elements in the initialization block.

Another way of initializing is using new operator.

int[] y=new int[]{1,2,3};

String variable also uses the both the way of initialization. But in Strings these two types have different meaning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM