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"};
No. The array is not being created twice. It is being created once and then it is being populated.
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"};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With