[英]String concatenation: + operator with String literal
為什么s3==s4
返回false
而s2==s3
返回true
。 分別為8和7。
1. String s="hello";`
2. String s1="he"+"llo";
3. String s2="hello"+123;
4. String s3="hello123";
5. String s4=ss+"123";
7. System.out.println(s==s1);//prints true
8. System.out.println(s2==s3);//prints true
9. System.out.println(s3==s4);//prints false
s + "123";
無法在編譯時評估,因此不是字符串實習的候選人。 (請注意,如果s
是final
那么它將是。)
因此,其引用將與s3
,因此輸出為false
。
由於字符串內嵌和表達式的編譯時可評估性,其他所有比較都為true
。
當您使用==
運算符檢查字符串的相等性時,它將檢查字符串在內存中的位置是否相同。
在情況2和4中,字符串“ hello”和“ hello123”將已經在字符串常量池中 (由於第1行和第3行),將被識別為等同於那些字符串,並且將在內存中使用相同的位置每。 簡單來說,它將創建一個String對象,並將其插入“ hello”和“ hello123”的兩個實例中。
當您這樣做時:
String s4=s+"123";
在運行時,它將為s4
創建一個新的內存位置,因為JLS表示:
在運行時通過串聯計算的字符串是新創建的,因此是不同的。
因此,存儲位置不同,因此輸出為false
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.