Arsen Alexanyan
Arsen Alexanyan

Reputation: 3141

Created String objects count

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.

Upvotes: 3

Views: 92

Answers (2)

Seelenvirtuose
Seelenvirtuose

Reputation: 20618

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.

Upvotes: 6

Aniket Thakur
Aniket Thakur

Reputation: 68915

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.

Upvotes: 1

Related Questions