0

I am a bit confused with the 2 lines below.

MyClass myobj[];
myobj = new MyClass[numberVariable];

i would expect in line 1 something like:

MyClass[] myobj;

But the code works and there is not error.

What is the explanation?

mike_x_
  • 1,840
  • 3
  • 31
  • 68

2 Answers2

3

As the JLS states

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

So even this is possible

float[][] f[][], g[][][], h[];

which is equivalent to

float[][][][] f;
float[][][][][] g;
float[][][] h;

and this is more readable, isn't it?

René Link
  • 43,842
  • 12
  • 98
  • 127
0

Both are valid syntax in Java, though MyClass[] myobj makes more sense to me, since you are declaring an array of type MyClass.

Eran
  • 374,785
  • 51
  • 663
  • 734