String s1 = "String";
String s2 = "String" + "";
String s3 = "" + s2;
System.out.println (s1 == s2);
System.out.println (s2 == s3);
System.out.println (s1 == s3);
true
false
false
Why do I get false values ? Shouldn't be s3 variable in String pool ? It's the same. It seems I don't understand String pool fully.
Since your Strings are not marked final, they will be created at runtime using StringBuilder (when you use + operation and concatenate Strings) and will NOT go into the String constants pool. If you want the Strings to go into StringPool when the class is loaded (just like literals), you should mark them as final and thus making them constants.
Like this :
public static void main(String[] args) {
final String s1 = "String"; // "String" will go into the constants pool even without `final` here.
final String s2 = "String" + ""; // Goes into the String constants pool now.
final String s3 = "" + s2; // Goes into the String constants pool now.
System.out.println (s1 == s2);
System.out.println (s2 == s3);
System.out.println (s1 == s3);
}
O/P :
true
true
true
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