views:

203

answers:

3

Hello guys, i tried something like this:


boolean funkyBoolean = true;
int array[] = funkyBoolean ? {1,2,3} : {4,5,6};

But this code won't even compile. Is there any explanation for this? isn't funkyBoolean ? {1,2,3} : {4,5,6} a valid expression? thank's in advance!

+4  A: 
boolean funkyBoolean = true;
int[] array = funkyBoolean ? new int[]{1,2,3} : new int[]{4,5,6};
Bozho
+20  A: 

You can only use the {1, 2, 3} syntax in very limited situations, and this isn't one of them. Try this:

int array[] = funkyBoolean ? new int[]{1,2,3} : new int[]{4,5,6};

By the way, good Java style is to write the declaration as:

int[] array = ...

EDIT: For the record, the reason that {1, 2, 3} is so restricted is that its type is ambiguous. In theory it could be an array of integers, longs, floats, etc. Besides, the Java grammar as defined by the JLS forbids it, so that is that.

Stephen C
Thanks for the explanation Stephen!
marcos
In JDK7 it looks as if `{1, 2, 3}` (in other situations) will be a set, with type determined by target typing (like generic methods, such as `Arrays.asList`).
Tom Hawtin - tackline
+2  A: 

An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values

That's what the Java Spec says (10.6). So the 'short' version (with the creation expression) is only allowed in declarations (int[] a = {1,2,3};), in all other cases you need a new int[]{1,2,3} construct, if you want to use the initializer.

Andreas_D
Thanks, that was helpfull!
marcos