0

I noticed recently that I can declare an array in java by putting the square brackets either after the type OR after the array variable name.

  1. float[] x
  2. float x[]

Are there any differences between these two, aside from the syntax?

As an aside, I stumbled upon a discovery that float[] x[] is actually initializing a two-dimensional array - at least according to Eclipse. Is that true?

Ahmad
  • 69,608
  • 17
  • 111
  • 137
kburbach
  • 761
  • 10
  • 26

5 Answers5

4

No difference. Both are valid in Java. The former is much more conventional for Java. Yes, that's a 2D array declaration, although terribly weird. Please write float[][] x.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173
3

If the variables are declared like you posted, then no, there is no difference:

  1. float[] x;
  2. float x[];

If you declare multiple variables in the same line, you will spot the difference:

  1. float[] x, y;
  2. float x[], y;

In last case:

  1. x and y are array of floats.
  2. x is an array of floats, while y is a float.

The recommended way to code: use 1 for ease of code readability.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
2

float val[] = new float[2]; does exactly the same as
float[] val = new float[2];.

From Java Language Specification

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 something like

float[] val[] = new float[2][3]

is correct (although unusual) for two dimensional array.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

float[] x and float x[] will both result in a single dimension array reference being created, float[] x is the preferred form.

float[] x[] will, indeed, create a 2 dimension array reference.

Ray Stojonic
  • 1,260
  • 1
  • 7
  • 11
0

No, there are no differences between the two syntaxes. You usually see the brackets on the variable in declarations and use the brackets on the type when using the type anonymously.

You're discovery is not surprising given that 'float[]' is a valid type specification and x[] declares an array of that type.

donleyp
  • 320
  • 1
  • 7