我是JAVA的新手,正在通過相等運算符。在嘗試了幾種操作數組合之後,我對Java中相等運算符(==)的兼容操作數的定義究竟是什麼有些困惑。關於JAVA中的相等運算符(兼容操作數)的查詢
int x = 23;
if (x == 23.3f) { // compiler accepts it. (may be because both are primitives)
int x = 23;
Double d = new Double(23.3);
if (x == d) { // compiler accepts it. (may be compatible pair of primitive and object reference)
int x = 23;
String s = "hello";
if (x == s) // compiler throws error - incompatible operands for == operator.
因此,它看起來對於我來說,對於相等運算符應該有一些兼容操作數的正式定義。請幫我澄清這個疑問。
字符串有'.equals'方法。並在你的最後一個'如果'它顯然,他們是不兼容的,因爲你是比較一個對象(字符串)與原始類型(int,long,double ...) – 2014-09-03 08:30:44
我明白.equals在那裏,但我的查詢是專門針對==的。如果你看到我的第二個例子,我將Object與Object(Double。)進行比較,然後編譯器接受它。 – pankaj 2014-09-03 08:39:00