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
  • 57,103
  • 20
  • 141
  • 208

2 Answers2

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

Community
  • 1
  • 1
Bogdan
  • 23,890
  • 3
  • 69
  • 61
0

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

Tobias Johansson
  • 378
  • 4
  • 11