“&&”和”&”都是java中的逻辑运算符,并且它们都表示“逻辑与”即“同真则真,有一假则假”,它们的区别在于”&&”具有短路功能,即如果左边是false,则右边的逻辑表达式不会执行。而”&”没有短路功能,无论左边是false还是true右边都会执行。

1 public class Test {
2     public static void main(String[] args) {
3         System.out.println(false&&(1/0==0)); //右边逻辑表达式会如果执行会有除0异常
4     }
5 }

 

1 false
2 
3 Process finished with exit code 0

比较上下两段代码即可发现区别。

1 public class Test {
2     public static void main(String[] args) {
3         System.out.println(false&(1/0==0)); //右边逻辑表达式会如果执行会有除0异常
4     }
5 }

 

1 Exception in thread "main" java.lang.ArithmeticException: / by zero
2     at Test.main(Test.java:6)
3 
4 Process finished with exit code 1

对于”||”和”|”也是一样的道理,”||”具有短路效果,若左边是true,右边逻辑表达式就不会执行,结果返回true;而”|”无论左边是false还是true右边都会执行。

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!