Java – add the difference between string literals and string objects
•
Java
What is the difference between adding string literal and string object?
for example
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@H_403_14@为什么s3 / s4没有指向与s5相同的位置?
Solution
Because S1 and S2 are not constant expressions, and because S1 and S2 are not final, the result is not interconnected, that is, another object is created to represent it, so the reference comparison generates false
JLS 3.10. 5 String Literals:
JLS 15.28 Constant Expression:
JLS 4.12. 4 defines the final variable
If S1 and S2 are declared final, S3 = = S5 will be true
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码