Ashutosh Sharma
Ashutosh Sharma

Reputation: 149

Java String pool object creation

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.

Upvotes: 4

Views: 723

Answers (2)

user207421
user207421

Reputation: 310915

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

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

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.

Upvotes: 8

Related Questions