I’m somewhat confused about the code below:
class BooksTestDrive {
public static void main(String [] args) {
String [] islands = new String[4];
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";
}
}
I was under the assumption that this would return a NullPointerException error because no object is initialized.
I assumed I would need to do
class BooksTestDrive {
public static void main(String [] args) {
String [] islands = new String[4];
islands[0] = new String();
// etc..
islands[0] = "Bermuda";
islands[1] = "Fiji";
islands[2] = "Azores";
islands[3] = "Cozumel";
}
}
Why is it okay here?
Why is the exception not thrown?
“Bermuda” is a String literal and
String str = "Bermuda";implies thatstris a new String object with the value “Bermuda”.The lines above do the same work, but with one difference, first string instance is managed by
Java String constant pooland the second one is not.