String array initialization in Java [duplicate]
If I declare a String
array:
String names[] = new String[3];
Then why can't we assign values to the array declared above like this:
names = {"Ankit","Bohra","Xyz"};
You can do the following during declaration:
String names[] = {"Ankit","Bohra","Xyz"};
And if you want to do this somewhere after declaration:
String names[];
names = new String[] {"Ankit","Bohra","Xyz"};
names[] = {"Ankit","Bohra","Xyz"};
is an initializer and used solely when constructing or creating a new array object. It cannot be used to set the array. You can use it when declared as:
String[] names= {"Ankit","Bohra","Xyz"};
You may also use:
names=new String[] {"Ankit","Bohra","Xyz"};
First up, this has got nothing to do with String
, it is about arrays.. and that too specifically about declarative initialization of arrays.
As discussed by everyone in almost every answer here, you can, while declaring a variable, use:
String names[] = {"x","y","z"};
However, post declaration, if you want to assign an instance of an Array:
names = new String[] {"a","b","c"};
AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.
However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.