【发布时间】:2011-11-04 04:58:24
【问题描述】:
可能的重复:
What's the difference between | and || in Java?
Difference in & and &&
我只是想知道 & 和 && 之间的区别是什么?
几天前,我为if 语句写了一个条件,看起来像:
if(x < 50 && x > 0)
但是,我将 && 更改为 & 并没有显示任何错误。有什么区别?
示例:我编译了这个简单的程序:
package anddifferences;
public class Main {
public static void main(String[] args) {
int x = 25;
if(x < 50 && x > 0) {
System.out.println("OK");
}
if(x < 50 & x > 0) {
System.out.println("Yup");
}
}
}
它打印出“OK”和“Yup”。如果它们都有效,那么我使用哪一个有关系吗?
【问题讨论】:
-
(不是完全同一个问题,但
&和&&的区别与|和||的区别一样。) -
所以,我想新的问题是:我怎么知道是选择 & 还是选择 &&?我理解 && 当且仅当第一个条件为真时才检查第二个条件(与 & 自动检查两者),但是选择一个而不是另一个有什么好处?
-
@Mike Gates 这是一个方便的例子 if(x!=null && x.length>0)... 如果我们在这里使用 & 而不是 && 那么如果 x 是null 我们会得到一个 NullPointerException,使用 && 可以防止这种情况发生,因为如果 x 为 null 则永远不会调用 x.length。
-
&& 短路了。