Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}; 
like image 597
Ankit Bohra Avatar asked Jul 07 '13 18:07

Ankit Bohra


People also ask

Can we initialize array two times?

No. The array is not being created twice. It is being created once and then it is being populated.


2 Answers

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"}; 
like image 178
Rohit Jain Avatar answered Sep 23 '22 03:09

Rohit Jain


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"}; 
like image 45
nanofarad Avatar answered Sep 23 '22 03:09

nanofarad