3

I am reading certification book and here I have faced with confusing problem. The book says that this line of code creates only one String object, but I think 2 objects are created. Am I right?

String summer = new String("Summer");

Doesn't the constant literal "Summer" created and placed in String constant Pool?

EDIT: Guys I'm getting confused I need exact answer. Here are different posts says both 1 object & 2 object is creating.

6
  • Yes, but as it's a string constant pool, the new String() will not create it again, because it's already there. The same reference will be used. Commented Jun 15, 2014 at 10:27
  • @TillHelge I think it will not use the same reference because ("Summer" == new String("Summer")) will always return false. Or I have misunderstood your post? Commented Jun 15, 2014 at 10:31
  • @ArsenAlexanyan to compare strings: "Summer".equals(new String("Summer")); Commented Jun 15, 2014 at 10:40
  • Yes I know but question is how many String objects are created. Commented Jun 15, 2014 at 10:42
  • one object, an one reference after the line of code summer Commented Jun 15, 2014 at 11:02

2 Answers 2

6

The creation might be the cause of your confusion. In fact, you are right: Two string instances are involved in the line

String summer = new String("Summer");

As there are two string instances involved, they must have been created somwhere and sometime.

The creation time is the big difference. The "Summer" is a constant which is loaded into the internal string pool when loading the class that contains this constant. So this internal string instance is created while loading the class.

The string object that the variable summer refers to is created while running the code that contains this line. That's it.

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

1 Comment

Wow interesting answer I will choose this after some suggestions. Thank You!
1
String summer = new String("Summer");

This will create only one instance of String. And it will not be in the String pool until you call intern() on it.

3 Comments

The instance is the new String(...). But how about "Summer" constant? Doesn't it created?
No it's not. And I hope by constant you are referring to String literal.
Yes I am reffering to String literal. Thanks!

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.