4

I have doubts that whether my concepts are clear in stringpool. Please study the following set of code and check if my answers are correct in number of objects created after the following set of statements:-

1)

String s1 = "abc";
String s2 = "def";
s2 + "xyz";

2)

 String s1 = "abc";
 String s2 = "def";
 s2 = s2 + "xyz";

3)

String s1 = "abc";
String s2 = "def";
String s3 = s2 + "xyz";

4)

String s1 = "abc";
String s2 = "def";
s2 + "xyz";
String s3 = "defxyz";

As per what i know conceptually, in all the 4 cases above, there will be 4 objects created after the execution of each set of the lines.

7
  • Tell us why, for example, in number 3 why there are 4 objects. Commented Aug 22, 2011 at 7:06
  • In the first three there are only 3 string objects each... Commented Aug 22, 2011 at 7:07
  • @djna: True. The compiler is free to use only three objects, since s2 + "xyz" can be evaluated at compile-time. Commented Aug 22, 2011 at 7:07
  • @John Skeet: Why not in the last one, too? Commented Aug 22, 2011 at 7:09
  • @Thilo, In the last one there are 4 distinct literals. I suppose we are not considering dead code elimination. :) Commented Aug 22, 2011 at 7:12

2 Answers 2

8

You cannot have an expression like s2 + "xyz" on its own. Only constants are evaluated by the compiler and only string constants are automatically added to the String literal pool.

e.g.

final String s1 = "abc"; // string literal
String s2 = "abc"; // same string literal

String s3 = s1 + "xyz"; // constants evaluated by the compiler 
                        // and turned into "abcxyz"

String s4 = s2 + "xyz"; // s2 is not a constant and this will
                        // be evaluated at runtime. not in the literal pool.
assert s1 == s2;
assert s3 != s4; // different strings.
Sign up to request clarification or add additional context in comments.

Comments

1

Why do you care? Some of this depends on how aggressively the compiler optimizes so there is no actual correct answer.

Comments

Your Answer

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.