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.

3
  • Not to be rude, but why do you need to know this? Commented Mar 12, 2017 at 11:05
  • 2
    Well, you are forgetting that "First"+"Second"+"Three"+"Four" is a compile-time constant which is compiled as FirstSecondThreeFour. Commented Mar 12, 2017 at 11:16
  • The first example has 4 strings and the second example has one (as the javac compiler does constant expression evaluation) Commented Mar 12, 2017 at 11:44

1 Answer 1

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.

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.