Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many String objects using new operator [duplicate]

When we use new operator to create a String object, I read that two Objects are created one Object is string constant pool and second one is in heap memory.

My question here is We are using new operator hence only one object should be created in Heap. Why then one more object has to be created in String Constant pool. I know Java stores String object whenever we not use new operator to create a String. For eg:

String s = "abc" . 

In this case only it will create in String constant pool.

String s2 = new String("abc") 

only one object hast to be created in heap and not in Constant pool.

Please explain why I am wrong here.

like image 999
user900721 Avatar asked Dec 04 '22 17:12

user900721


2 Answers

We are using new operator hence only one object should be created in Heap.

Sure - the new operation only creates one object. But its parameter is a String literal, which already represents an object. Any time you use a String literal, an object was created for that during class loading (unless the same literal was already used elsewhere). This isn't skipped just because you then use the object as a parameter for a new String() operation.

And because of that, the new String() operation is unnecessary most of the time and rarely used.

like image 85
Michael Borgwardt Avatar answered Dec 21 '22 23:12

Michael Borgwardt


See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28

Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern

Thus when you write

String s2 = new String("abc")

The Compile-time constant expression "abc" will be interend.

like image 42
Oded Peer Avatar answered Dec 22 '22 01:12

Oded Peer