Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, when is the {a,b,c,...} array shorthand inappropriate, and why?

If you're defining a variable, it appears to be perfectly valid to declare/define a variable as follows:

    double[][] output = {{0,0},{1,0}};

But if you're returning a value, it appears to be invalid to write the following:

    public double[] foo(){
      return {0,1,2}
    }

I would have thought that internally, both of these would have been performing the same action. Eclipse, at least, disagrees. Does anyone know what the difference is, and where else it can be seen, or why it would be beneficial to accept the former example and reject the latter?

Edit: okay, so it's appropriate when you're initializing, but I don't see any ambiguity... couldn't the JVM interpret the type of variable from the name of the variable (in the case of redefining already initialized variables) or when returning (where the JVM could just look at the return type of the function)? What makes initialization a special case of a rule that would prohibit implicit type? What makes the general rule require explicit type?

like image 543
John P Avatar asked Jul 29 '13 20:07

John P


People also ask

What is difference between a [] and [] A?

What is the difference between int[] a and int a[] in Java? There is no difference in these two types of array declaration. There is no such difference in between these two types of array declaration. It's just what you prefer to use, both are integer type arrays.

Is it int [] array or int array []?

They are semantically identical. The int array[] syntax was only added to help C programmers get used to java. int[] array is much preferable, and less confusing. The [] is part of the TYPE, not of the NAME.

Which symbol is used to declare an array in Java?

Array elements must be separated with Comma(,)s.

Is int * the same as array?

The difference is when you do int array[100] , a memory block of 100 * sizeof(int) is allocated on the stack, but when you do int *array , you need to dynamically allocate memory (with malloc function for example) to use the array variable. Dynamically allocated memory is on the heap, not stack.


2 Answers

You can use braces notation only at the point of declaration, where compiler can infer the type of array from the declaration type.

To use it anywhere else you need to use Array Creation Expression:

return new double[] {0,1,2};
like image 54
Rohit Jain Avatar answered Oct 13 '22 19:10

Rohit Jain


It's only acceptable during a declaration. You can, however, use new double[] {0, 1, 2}.

JLS §10.6:

An array initializer may be specified in a declaration, or as part of an array creation expression.

An array creation expression is the new double[] { } syntax.

like image 26
Jeffrey Avatar answered Oct 13 '22 19:10

Jeffrey