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