0

My questions is regarding string pool in java.

Case 1:

StringBuilder sb = new StringBuilder();
sb.append("First");
sb.append("Two");
sb.append("Three");
sb.append("Four");

Case 2:

StringBuilder sb = new StringBuilder();
sb.append("First"+"Second"+"Three"+"Four");

How many string objects will be there in string pool after execution of each above 2 cases?(Note : Assume string pool have 0 object before each case.)

My assumptions=>

In 1st case:

String pool will have 4 string objects at the end of 1st case. How? Explanation: String "First" will get created, it will add in string pool & sb will be modified. Then another string object "Two" will get created, will keep it in string pool & sb will get modified. In same way, at the end of the first case, string pool will have 4 string objects.

In 2nd case: String pool will have 7 string objects. How? Explanation: String "First" & "Two" will get created in pool, then since we are concatenating "First" & "Two", third string object "FirstSecond" will get created in string pool. In the same way, at the end of the 2nd case, string pool will have 7 objects.

Correct me if I am wrong.

1 Answers1

1

You are wrong. In the first example you'll have four string literals in the pool, not created at run time but at compile time and added to the pool at class initialization time. The second example will have one string literal in the pool because the concatenation is a constant expression, which the compiler evaluates and embeds as a single literal in the bytecode.

In the more general case of runtime evaluation, when it's not a constant expression, you still won't get seven strings. For example, in

String foo = getPrefix() + getName() + " foo " + getSuffix();

you concatenate four strings into one, for a total of five, not necessarily interned. Not seven, because one-line string concatenations are implemented as StringBuilder#append calls, and there are no intermediate string instances, just the result one at the end.

Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
  • And please note that any Java compiler is *required* to to do this. It is mandated by the Java Language Specification. It isn't just a quirk of a current compiler. – user207421 Mar 12 '17 at 12:08