nail fei
nail fei

Reputation: 2319

the difference between with new or without when build array

I know that there exist two ways to build an array:

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

and by now everything is ok.

But when using for loop to process the data of array. Something appear.

as for this way:

for(int data:a){}

everything is ok,
but about the below way, surprise arise:

for(int data:{1,2,3}){}

it cant pass compile. and the error information is:


Multiple markers at this line
- Syntax error, insert "}" to complete ArrayInitializer
- Syntax error, insert "; ; ) Statement" to complete ForStatement
- Type mismatch: cannot convert from int[] to int
- Syntax error on token ":", = expected

I want to figure out why, and further I want to know whether the array is in stack or heap memory when without new keyword? and I know it exist heap memory when with new keywords.

Upvotes: 0

Views: 88

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074839

In a variable initialization, the two forms have exactly the same result.

The short form (called an array initializer; JLS§10.6) can only be used in an initialization, though, not as a freestanding value, which is why your for example doesn't work.

Upvotes: 6

Related Questions