作者clplusegg ()
看板java
標題[問題] String 老問題...
時間Mon Jul 15 23:36:58 2013
不好意思,最近剛在學習JAVA,看到良葛格提到的immutable string,
原本看完還是不太懂,爬過板上文章後,從良葛格提供的code改了一小段去驗證自己
想的對不對。如下:
public class StringIntern {
public static void main(String[] args) {
String str1 = "fly";
String str2 = "flyweight";
String str3 = str1 + "weight";
System.out.println(str3 == str2);
}
}
答案會是false,我想問的是在str3的地方,是因為str1不會在編譯時期被compiler視為
"fly",所以str3要指向的值在string pool裡面沒撈到,導致最後答案是false?
還是其實str3也會被create成一個object?
麻煩板上各位前輩解惑! 謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 111.250.171.73
→ tsungchic:比較方式不對,請用str3.equals(str2) 07/16 00:04
→ tsungchic:"=="是指兩個變數是否指向相同物件實體,當然是false 07/16 00:08
→ tkcn:你要不要先做 str3="str"+"weight" 的測試,然後推論看看呢? 07/16 00:12
→ tkcn: 打錯 "fly" 07/16 00:14
推 LonelyLouis:同樓上 因為str3 與 str2 是不同的物件 當然是false 07/16 01:01
→ coolcomm:"fly"+"weight"好像會在編譯時期被處理 所以str2==str3 07/16 10:29