Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

References on String

Tags:

java

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.

like image 400
Imugi Avatar asked Jan 25 '26 18:01

Imugi


1 Answers

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
like image 58
TheLostMind Avatar answered Jan 28 '26 11:01

TheLostMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!