-6

What is the difference, if any, between these two ways of creating an array in Java?

Method 1:

String[] s = new String[];

Method 2:

String s[];

Thanks in advance.

Jason C
  • 38,729
  • 14
  • 126
  • 182
Yehuda Gutstein
  • 381
  • 10
  • 27

2 Answers2

4

There are a few ways to interpret your question,

// this was missing a size. So we need to add one.
int x = 10;
String []s = new String[x];
String s[] = new String[x]; // This is the same as the previous line.

The other form type of question is this,

//These are two null arrays.
String s[];
String []s;

So you can put the brackets before (or after) the array name in Java. That is a convenience the compiler offers, they're equivalent.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2
String[] s = new String[length];

This creates a new array of length length and initializes its values with nulls.

String s[];

This declared a new array variable, which has the value of null. It needs to be initialized before it can be used, and because it hasn't been initialized, it can't be said to have a length.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • 5
    This isn't valid code, not without a size assigned to the created array. If such a size were given in method 1, then your answer there would be correct. Method 2 does *not* create a new array; it just creates a new variable of type `String[]`. – Michael Petrotta Apr 20 '14 at 04:32
  • 3
    I see what you're trying to do; I've edited your answer further. – Michael Petrotta Apr 20 '14 at 04:38