字符串引用

Imu*_*ugi 3 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
Run Code Online (Sandbox Code Playgroud)

为什么我会得到错误的价值观?字符串池中不应该是s3变量?一样的.好像我完全不了解String pool.

The*_*ind 6

由于您的字符串未标记final,它们将在运行时使用StringBuilder(当您使用+操作并连接字符串时)创建,并且不会进入字符串常量池.如果你希望在加载类时将字符串转换为StringPool(就像文字一样),你应该将它们标记为final并因此使它们成为常量.

像这样 :

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);
}
Run Code Online (Sandbox Code Playgroud)

O/P:

true
true
true
Run Code Online (Sandbox Code Playgroud)