java - 两个字符串引用引用相同的字符串,但比较时,结果返回 false。

标签 java string

s2和s3的值为“ab”,该字符串存储在字符串池中。 根据文档 s2==s3 应该返回 true,但它返回 false。 为什么?

 public class Sample {
      public static void main(String[] args) {
      String s="a";
      String s1="b";
      String s2=s+s1;
      String s3="ab";
      System.out.println(s2==s3);
   }
}

最佳答案

根据Java语言规范§15.18.1

15.18.1 String Concatenation Operator +

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).

+ 将始终生成一个新字符串,除非表达式是常量。常量表达式的一个示例是"a"+ "b"。您的表达式不是常量,因为它包含非最终变量。

第 12.5 节对此进行了更明确的说明:

Execution of a string concatenation operator + (§15.18.1) that is not part of a constant expression (§15.28) always creates a new String object to represent the result.

关于java - 两个字符串引用引用相同的字符串,但比较时,结果返回 false。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51075542/

相关文章:

java - 在 SSL 中使用 Spring BOOT 进行 SOAP 身份验证

java - 执行的程序挂起(可能是由于输出太多)

string - 多列上的 pandas 数据框 sort_values 并不总是有效

c++ - 模板 char/wchar_t、string/wstring、cout/wcout、regexp/wregex(或任何可能的解决方法)

python - 反转字符串但将字符对放在一起

java - liferay的选项卡元素如何控制打开哪个选项卡

java - 如何比较带有 ü、ć、š 等特殊字符的字符串?

java - 在java中使用正则表达式从长字符串中提取特定值或子字符串

python - pyqt : Variable values in QMessageBox output?

java - 通用构造函数的好处