可能重複:
Difference Between Equals and ==
In JDK 1.6, can String equals operation can be replaced with ==?
How do I compare strings in Java?意外的結果,比較兩個Java的字符串與 「==」 當
雖然與Java的字符串玩耍,我沒想到以下結果:
public class Sandbox {
public static void main(String[] args) {
String a = "hello";
String b = "hello";
System.out.println(a == b); //true Why?, a and b both are seperate Objects
System.out.println(a == "hello"); //true Why?
System.out.println(a == new String(b)); //false As expected
}
}
我期望所有的都是錯誤的,因爲「==」比較引用。爲什麼會有這個結果
當我更改String b = "world"
時,System.out.println(a == b);
返回false
。看起來好像字符串對象的內容正在被比較。
由於Java 7可以比較switch-case-Statements中的字符串,我認爲它可能與Java版本有關。但是如here所述,在比較Switch-Case中的字符串時會調用equals-Methode。
請閱讀[this](http://stackoverflow.com/questions/971954/difference-between-equals-and)。 – mre 2012-04-12 11:42:43
總之,一些字符串被實現(即緩存)並引用同一個對象,這就解釋了爲什麼==可以工作。但是你不能依賴這種機制,而應該使用equals。 – assylias 2012-04-12 11:45:07
底線是,因爲字符串仍然是對象,所以在絕大多數情況下,您應該使用「equals」方法。 – 2012-04-12 11:49:04