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.
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.
Why do you care? Some of this depends on how aggressively the compiler optimizes so there is no actual correct answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With