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,900
  • 3
  • 35
  • 69

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
  • 48,224
  • 13
  • 108
  • 140
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
  • 387,369
  • 54
  • 702
  • 768