2

Anyone can tell me in the below array intialization have any difference.

String[] emptyName = new String[]{"hi","hello","what"};
String[] emptyName={"hi","hello","what"};
String emptyName[] = new String[]{"hi","hello","what"};
String emptyName[] = new String[]{new String("hi"),new String("hello"),new String("what")};

Thanks

user3062776
  • 157
  • 10

5 Answers5

2

There is no difference. It's just a Syntactic sugar in array declaration.

I prefer the less confusing way, which is second type.

wait ... look carefully. Youl'll see the difference now. The below example shows how the style of initialization matters.

There is a method

 private  void methodName(String[] strs){
          // do something
      }

While calling them, see how there is a difference.

methodName(new String[] {"hi","hello","what"}); //  inline creation 
methodName({"hi","hello","what"});     //Error. Type missing now
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
2

There is no difference between String[] someArray vs String someArray[]. Everything after the equals sign is just declaring what the array will be initialized with.

SnakeDoc
  • 11,211
  • 13
  • 56
  • 86
1

Apart from the notation, all the above will act the same code-wise and compilation-wise :-)

Kelevandos
  • 6,561
  • 24
  • 44
1

There is not difference between the four declarations except for the syntax in the String and the Array declaration.

String

The most direct way to create a string is to write:

String foo = "hi";

In this case, "hi" is a string literal —a series of characters in your code that is enclosed in double quotes.

As with any other object, you can create String objects by using the new keyword and a constructor.


Array

From (JLS §10.2)

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.

String[] emptyName = String emptyName[] (Note that the square brackets should be a part of the type, not the variable so you should not use the second array declaration)

Pier-Alexandre Bouchard
  • 4,937
  • 5
  • 33
  • 67
1

From Java Language specification: http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf

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. For example: byte[] rowvector, colvector, matrix[]; This declaration is equivalent to: byte rowvector[], colvector[], matrix[][];