3

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

Utkarsh Saraf
  • 475
  • 8
  • 31

2 Answers2

3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
-2

same interned object will be used by str1 resulting in 3 objects , try to undertnad using equals methods

  • `str1` has nothing to do with interning, and what exactly does the `equals()` method have to do with the question? – user207421 Mar 23 '17 at 10:33
  • let's assume class String has a field, private char[] data. Then after String str= new String("xyz"); the following will be true: str.equals("xyz"), str != "xyz", str.data == "xyz".data. I.e. both fields refer to the same array.My point is use equals() and == method to understand object creation in string pool and heap. – Anurag Kumar Mar 23 '17 at 10:44