0

I am bit confused about string object creation. Can someone tell me, how many String objects get created in below 2 cases?

1)

String s = new String("abc");
s = s + "xyz";

2)

String s = new String("abc");
String s1 = "xyz";
Grijesh Chauhan
58.6k20 gold badges145 silver badges214 bronze badges
asked Mar 1, 2015 at 16:13

2 Answers 2

5

First case:

String s = new String("abc");
s = s + "xyz";

You have:

  • "abc" is a string literal and is interned => one string instance
  • String s = new String("abc") creates another string "abc" that is stored in the heap => another string instance;
  • in s = s + "xyz"; you have "xyz" as one string literal which is interned and another string on the heap is built with the concatenated value "abcxy" which is another string.

You have 4 strings created in total with the old value of s being discarded. You remain with the "abc" and "xyz" interned strings and string "abcxyz" which is stored in s.

Second case:

String s = new String("abc");
String s1 = "xyz";

You have:

  • "abc" is a string literal and is interned => one instance
  • String s = new String("abc") creates another string "abc" that is stored in the heap => another instance
  • String s1 = "xyz"; you have "xyz" as one string literal which is interned and s1 points to it.

You have 3 strings created in total. You remain with two interned strings "abc" and "xyz", another "abc" stored in the heap and referred by s while s1 points to the interned "xyz".

You might also have a look at this for some basic explanations: The SCJP Tip Line: Strings, Literally

answered Mar 1, 2015 at 17:19
Sign up to request clarification or add additional context in comments.

Comments

0

After the execution of 1) you have one String object, after 2) you have two.

answered Mar 1, 2015 at 16:17

5 Comments

Thanks for answer. Just want to know, is there any other ways by which we can create a String object apart from above two.
String myStr = "This is my String";
This is same as my 2nd option. Do we have any 3rd scenario or case in which, an String object will be creats
Sorry i read wrong. I can not see any other ways. It would be like this. String str = new String(); str = "Some text";
This is not the correct answer. Strings in Java are immutable, so every instance of modification or concatenation creates new String objects.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.