java – 添加String Literals和String对象之间的区别
作者:互联网
添加String Literal和String Object之间有什么区别?
例如
String s1 ="hello";
String s2 ="hello1";
String s3 ="hello" + "hello1";
String s4 ="hellohello1";
String s5 = s1 + s2;
System.out.println(s3 == s4); // returns true
System.out.println(s3 == s5); // return false
System.out.println(s4 == s5); // return false
为什么s3 / s4没有指向与s5相同的位置?
解决方法:
因为s1 s2不是常量表达式,因为s1和s2不是final,因此它的结果不是interned,即创建另一个对象来表示它,因此引用比较产生false.
String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are “interned” so as to share unique instances, using the method String.intern.
JLS 15.28 Constant Expression:
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- …
- Simple names that refer to constant variables (§4.12.4).
JLS 4.12.4定义了最终变量.
如果将s1和s2声明为final,则s3 == s5将为true.
标签:java,string,literals 来源: https://codeday.me/bug/20190730/1578910.html