Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String pool object creation

Tags:

java

string

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.

like image 621
Ashutosh Sharma Avatar asked Jan 19 '23 22:01

Ashutosh Sharma


2 Answers

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.
like image 149
Peter Lawrey Avatar answered Jan 29 '23 20:01

Peter Lawrey


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

like image 34
user207421 Avatar answered Jan 29 '23 20:01

user207421