Utkarsh Saraf Utkarsh Saraf -4 years ago 89
Java Question

Special Case of String interned in Java

I have following two lines in Java code :

String str = new String("My place")
String str1 = new String("My place")

It is clear that new String("My place") creates two object,one due to interning and another due to new but i am confused as here the argument is having same literal so whether same interned object is being used by str1 resulting in 3 objects or different resulting in 4 objects

Answer Source

Interning of string literals is automatic in Java, so the same interned object will be used in both constructors, so there will be three objects, not four.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download