欢迎来到王晨的博客

脚踏实地,不断坚持,没有终点,永远在路上!!!
扩大
缩小

逻辑运算符

&&和&的区别(与运算)

&&(短路与)

前后两个操作数必须都是true才返回true,否则返回false。

1 //5 > 3 返回 true , '6' 转换为整数 54, '6' > 10 返回 true, 求与后返回true 
2 
3 System.out.println(5 > 3 && '6' > 10);

 

1 int i = 4;
2  if ((i++ > 6) && (i++ < 9)) {
3  System.out.println(i);
4  }
5  System.out.println(i) ;

 

&(不短路与)

无论左边是false还是true,右边都执行。

1 int i = 4;
2 if ((i++ > 6) & (i++ < 9)) {
3 System.out.println(i);
4 }
5 System.out.println(i);

 

||和|的区别(或运算)

||(短路或)

只要两个操作数中有一个是true,就可以返回true,否则返回false。

1 //4 > 5 返回 true, 'c' > 'a' 返回true, 求或后返回true
2 
3 System.out.println(4 >=5 || 'c' > 'a');

 

 1 //4 > 5 返回 true, 'c' > 'a' 返回true, 求或后返回true
 2  
 3  System.out.println(4 >=5 || 'c' > 'a');
 4  
 5  //定义变量c,d,并为连个变量赋值
 6  int c = 5;
 7  int d = 10;
 8  //对 c > 4 || d++ > 10 求或运算
 9  if (c > 4 || d++ > 10) {
10  //输出c的值是5,d的值是10
11  System.out.println("c的值是:" + c + ",d的值是:" + d);
12  }

 

|(不短路或)

无论左边是false还是true,右边都会执行。

1 //定义变量a,b,并为连个变量赋值
2 int a = 5;
3 int b = 10;
4 //对 a > 4 和 b++ > 10 求或运算
5 if (a > 4 | b++ > 10) {
6 //输出a的值是5,b的值是11
7 System.out.println("a的值是:" + a + ",b的值是:" + b);
8 }

 

!(非)

只需要一个操作数,如果操作数为true,则返回false;如果操作数为false,则返回true。

1 //直接对false求非运算,将返回true
2 
3 System.out.println(!false);

 

^ (异或)

当两个操作数不同时才返回true, 如果两个操作数相同则返回false。

1 //4 >=5返回false,'c'>'a'返回true,两个不同数的操作数求异或返回true
2 
3 System.out.println(4 >= 5 ^ 'c' > 'a');

 

posted on 2018-01-15 22:22  王、晨  阅读(99)  评论(0编辑  收藏  举报

导航