一、逻辑&与短路&&的区别
- 总的来说区别是体现在,只有这两个运算符的左边为false的时候会有区别,看如下代码
1.逻辑&的运算
boolean a = true;
boolean b = false;
int i = 10;
if(b&(i++)>0)
System.out.print(i); //输出11,即&的右边有进行运算
else
System.out.print(i);
2.短路&&的运算
boolean a = true;
boolean b = false;
int i = 10;
if(b&&(i1++)>0)
System.out.print(i); //输出10,即&&的右边没有运算
else
System.out.print(i);
小结一下:
&:不管&的左边是true还是false,右边都会进行运算
&&: 只要左边是false,右边就不会进行运算
一半情况下都会选择&&,因为这样可以提高效率,也可以进行异常处理,当右边产生异常的时候,同样可以跳过。
二、逻辑| 与短路||的区别
- 和上面的类似,只不过这两者是只有当左边为true的时候,才会有区别,看如下代码
1.逻辑 | 的的运算
boolean a = true;
int i = 10;
if(a|(i++)>0)
System.out.print(i); //输出11,即的右边有进行运算
else
System.out.print(i);
2.短路 || 的运算
boolean a = true;
int i = 10;
if(a||(i++)>0)
System.out.print(i); //输出10,即||的右边没有运算
else
System.out.print(i);
小结:
| : 当左边为true时,右边同样进行运算
|| : 当左边为true时,右边不再进行运算