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

查看:136
本文介绍了&有什么区别?和&&在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,唯一的区别是即使LHS操作数为false,它也会检查RHS操作数.

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),并且只有在为true时才评估(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天全站免登陆