和 之间的区别和&&在Java中?
我只是想知道 & 和 && 之间的区别是什么?
几天后,我为 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”。那么,如果两者都有效,我使用哪一个有关系吗?
Possible Duplicates:
What's the difference between | and || in Java?
Difference in & and &&
I was just wondering what the difference between & and && is?
A few days I wrote a condition for an if
statement the looked something like:
if(x < 50 && x > 0)
However, I changed the && to just & and it showed no errors. What's the difference?
Example: I compiled this simple program:
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");
}
}
}
It printed "OK" and "Yup". So does it matter which one I use if they both work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
&
是按位。&&
是合乎逻辑的。&
对运算的两边进行求值。&&
计算操作的左侧,如果为true
,则继续计算右侧。&
is bitwise.&&
is logical.&
evaluates both sides of the operation.&&
evaluates the left side of the operation, if it'strue
, it continues and evaluates the right side.&是按位 AND 运算符比较每个操作数的位。
例如,
&&是逻辑 AND 运算符,仅比较操作数的布尔值。它需要两个表示布尔值的操作数并对它们进行惰性求值。
& is bitwise AND operator comparing bits of each operand.
For example,
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
&& == 逻辑与
& = 按位与
&& == logical AND
& = bitwise AND
'&'执行这两项测试,而 '&&'如果第一个测试也为真,则仅执行第二个测试。这称为短路,可以被视为一种优化。这对于防止空值(NullPointerException)特别有用。
'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).