programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Subtle Array question

Greenhorn
Posts: 14
• Number of slices to send:
Optional 'thank-you' note:
Is there any subtle differences between the following two declarations?
int [] x = {1, 2, 3};
int [] x = new int[] {1, 2, 3};

Author & Gold Digger
Posts: 7617
6
• Number of slices to send:
Optional 'thank-you' note:
I don't think there is any difference, this is so to speak, syntactic sugar in my opinion.

Greenhorn
Posts: 18
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by Danny Duong:
Is there any subtle differences between the following two declarations?
int [] x = {1, 2, 3};
int [] x = new int[] {1, 2, 3};

Yes.
The first is implicit initialization of an array.
You use the new int[] to initialize the array object itself. That is, if you want your array to contain 3 elements, you make use of the new operator in this way,
int [] x;
x = new int[3];
Then, you can explicitly initialize each element of the array object, referenced by a primitive variable 'x'.
int [] x = new int[] {1, 2, 3}; // will
// give compile-time error
All the best Danny

Valentin Crettaz
Author & Gold Digger
Posts: 7617
6
• Number of slices to send:
Optional 'thank-you' note:
Ikechukwu,
I don't understand why you say that
int [] x = new int[] {1, 2, 3};
gives a compiler error.
That code is perfectly legal. It compiles and runs fine. Please shed some light on this.
An illegal statement would be to specify the array length AND the array initializer at the same time, as in
int[] arr = new int[3] {1,2,3};
Please refer to JLS 10 Arrays
[ December 16, 2002: Message edited by: Valentin Crettaz ]

Greenhorn
Posts: 23
• Number of slices to send:
Optional 'thank-you' note:
Hi Danny,
I agree with Valentine. There is really no difference in terms of construct and initialization between the two array statements:
int [] x = {1, 2, 3};
int [] x = new int[] {1, 2, 3};
But the primary purpose of the new int[] {1, 2, 3} is for anonymous array since you can create it without declaring an array name.
Also, int [] x = new int[] {1, 2, 3}; // will NOT give compile-time error
Hope that makes sense.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?