我一直认为Java中的&&操作符用于验证其布尔操作数是否为真,并且&操作符用于对两个整数类型进行逐位操作。

最近我知道&运算符也可以用来验证它的两个布尔操作数是否为真,唯一的区别是即使LHS操作数为假,它也会检查RHS操作数。

Java中的&操作符内部重载吗?或者这背后还有其他的概念吗?


当前回答

&&是短路运算符,而&是与运算符。

试试这个。

    String s = null;
    boolean b = false & s.isEmpty(); // NullPointerException
    boolean sb = false && s.isEmpty(); // sb is false

其他回答

boolean a, b;

Operation     Meaning                       Note
---------     -------                       ----
   a && b     logical AND                    short-circuiting
   a || b     logical OR                     short-circuiting
   a &  b     boolean logical AND            not short-circuiting
   a |  b     boolean logical OR             not short-circuiting
   a ^  b     boolean logical exclusive OR
  !a          logical NOT

short-circuiting        (x != 0) && (1/x > 1)   SAFE
not short-circuiting    (x != 0) &  (1/x > 1)   NOT SAFE

我想我的答案可以更容易理解:

&和&&之间有两个区别。

如果他们使用逻辑与

&和&&可以是逻辑与,当&或&&左右表达式结果全部为真时,整个运算结果可以为真。

当&和&&作为逻辑与时,有区别:

当使用&&作为逻辑与时,如果左边的表达式结果为假,右边的表达式将不会执行。

举个例子:

String str = null;

if(str!=null && !str.equals("")){  // the right expression will not execute

}

如果使用&:

String str = null;

if(str!=null & !str.equals("")){  // the right expression will execute, and throw the NullPointerException 

}

还有一个例子:

int x = 0;
int y = 2;
if(x==0 & ++y>2){
    System.out.print(“y=”+y);  // print is: y=3
}

int x = 0;
int y = 2;
if(x==0 && ++y>2){
    System.out.print(“y=”+y);  // print is: y=2
}

&可以用作位运算符

&可以用作位与运算符,&&不能。

按位AND“&”运算符当且仅当两个位都在时产生1 它的操作数是1。然而,如果两个比特都是0,或者两个比特都不相同,那么这个运算符产生0。更精确地说,“&”运算符如果两位中的任何一位为1,则返回1,如果其中任何一位为0,则返回0。

来自维基页面:

http://www.roseindia.net/java/master-java/java-bitwise-and.shtml

如JLS(15.22.2)中所述:

When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary. For &, the result value is true if both operand values are true; otherwise, the result is false. For ^, the result value is true if the operand values are different; otherwise, the result is false. For |, the result value is false if both operand values are false; otherwise, the result is true.

“诀窍”在于&是一个整数位运算符,也是一个布尔逻辑运算符。为什么不呢,把这个作为运算符重载的例子是合理的。

这取决于参数的类型……

对于整数参数,单个&号(“&”)是“逐位AND”操作符。双&号(“&&”)只用于两个布尔参数。

对于布尔参数,单个&号构成(无条件)“逻辑与”运算符,而双&号(“&&”)是“条件逻辑与”运算符。也就是说,单&号总是计算两个参数,而双&号只在第一个参数为真时计算第二个参数。

对于所有其他参数类型和组合,应该发生编译时错误。

除了&&和||是短路外,在混合这两种形式时,还要考虑运算符优先级。 我认为每个人都不会立即看出result1和result2包含不同的值。

boolean a = true;
boolean b = false;
boolean c = false;

boolean result1 = a || b && c; //is true;  evaluated as a || (b && c)
boolean result2 = a  | b && c; //is false; evaluated as (a | b) && c