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/