String array initialization in Java

JavaArraysString

Java Problem Overview


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"};

Java Solutions


Solution 1 - Java

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"};

Solution 2 - Java

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"};

Solution 3 - Java

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.

Solution 4 - Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

Solution 5 - Java

It is just not a valid Java syntax. You can do

names = new String[] {"Ankit","Bohra","Xyz"};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkit BohraView Question on Stackoverflow
Solution 1 - JavaRohit JainView Answer on Stackoverflow
Solution 2 - JavananofaradView Answer on Stackoverflow
Solution 3 - JavazEroView Answer on Stackoverflow
Solution 4 - JavaSwiftMangoView Answer on Stackoverflow
Solution 5 - JavafastcodejavaView Answer on Stackoverflow