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

1
  • 3
    3 objects...because of the literal being the same. Commented Mar 23, 2017 at 10:29

2 Answers 2

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.

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

Comments

-2

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

2 Comments

str1 has nothing to do with interning, and what exactly does the equals() method have to do with the question?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.