& 和有什么区别和&&在 Java 中? [英] What is the difference between & and && in Java?

查看:28
本文介绍了& 和有什么区别和&&在 Java 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以为Java中的&&操作符是用来验证它的布尔操作数是否为true& 运算符用于对两种整数类型进行按位运算.

I always thought that && operator in Java is used for verifying whether both its boolean operands are true, and the & operator is used to do Bit-wise operations on two integer types.

最近我知道&操作符也可以用来验证它的两个布尔操作数是否为true,唯一的区别是它甚至会检查RHS操作数如果 LHS 操作数为假.

Recently I came to know that & operator can also be used verify whether both its boolean operands are true, the only difference being that it checks the RHS operand even if the LHS operand is false.

Java 中的 & 运算符是否在内部重载?或者这背后是否有其他概念?

Is the & operator in Java internally overloaded? Or is there some other concept behind this?

推荐答案

&<-- 验证两个操作数
&&<-- 如果第一个操作数的计算结果为假,则停止计算,因为结果将为假

& <-- verifies both operands
&& <-- stops evaluating if the first operand evaluates to false since the result will be false

(x != 0) &(1/x > 1) <-- 这意味着评估 (x != 0) 然后评估 (1/x > 1) 然后做 &.问题是对于 x=0 这将引发异常.

(x != 0) & (1/x > 1) <-- this means evaluate (x != 0) then evaluate (1/x > 1) then do the &. the problem is that for x=0 this will throw an exception.

(x != 0) &&(1/x > 1) <-- 这意味着评估 (x != 0) 并且只有当这是真的时才评估 (1/x > 1) 所以如果你有 x=0 那么这是完全安全的,并且如果 (x != 0) 评估为 false 整个事情直接评估为 false 而不评估 (1/x > 1).

(x != 0) && (1/x > 1) <-- this means evaluate (x != 0) and only if this is true then evaluate (1/x > 1) so if you have x=0 then this is perfectly safe and won't throw any exception if (x != 0) evaluates to false the whole thing directly evaluates to false without evaluating the (1/x > 1).

exprA |exprB <-- 这意味着先评估 exprA 然后评估 exprB 然后执行 |.

exprA | exprB <-- this means evaluate exprA then evaluate exprB then do the |.

exprA ||exprB <-- 这意味着评估 exprA 并且只有当这是 false 时才评估 exprB 并执行 ||.

exprA || exprB <-- this means evaluate exprA and only if this is false then evaluate exprB and do the ||.

这篇关于&amp; 和有什么区别和&amp;&amp;在 Java 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆