1

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?

4 Answers 4

3

"Bermuda" is a String literal and String str = "Bermuda"; implies that str is a new String object with the value "Bermuda".

String str = "Bermuda";
String str = new String("Bermuda");

The lines above do the same work, but with one difference, first string instance is managed by Java String constant pool and the second one is not.

Sign up to request clarification or add additional context in comments.

3 Comments

I see. So if It was lets say NotAStringClass[] islands = new NotAStringClass[4]; then passing a string to islands[0] would not work, correct?
@Lion you don't see, sorry. islands[0] = "Bermuda"; and islands[0] = new String("Bermuda"); functionally do the same thing and both will work, but created String objects for these 2 assignments live in different places in memory.
Got it. Your answer along with Hassan's helped me get it. Thanks :)
0

Exception is not thrown because you are using "static" strings whose memories are implicitly created and the references assigned to islands[i]

2 Comments

I get it now. Thanks, you and Shekasteh helped me understand it. I can only select one answer so I'll just pick his but thank you both.
Any time Lion! I am happy that you understood the concept.
0

You're doing nothing wrong, the compiler honors that and it's running also.

When you're using static string literals the string object is created implicit. You can also try this out with the debugger, your String "Bermuda" has an object id.

Comments

0

The Exception that you asked about occurs when you declare a variable but did not create an object. In the line "String [] islands = new String[4]; " the new keyword is used to instantiate (or create) an object of type Integer and the pointer variable islands is assigned this object. So you will not get an exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.