java学习:逻辑运算相关

一、逻辑运算的相关符号

 二、相关知识点

1、逻辑运算符用于连接布尔型表达式,在Java中不可以写成3<x<6,应该写成x>3 & x<6 。

2、“&”和“&&”的区别:
单&时,左边无论真假,右边都进行运算;
双&时,如果左边为真,右边参与运算,如果左边为假,那么右边不参与运算(可以理解为从左往右计算,如果左边是false就不会往右在判断了,所以右边也就不参与计算了)。

public class Test {
    public static void main(String[] args) {   
        int t = 10;
        int s = 11;        
        System.out.println(++s == 12 && t == 10);   //  输出结果是false
        System.out.println(s);                      // 输出12
        
        int m = 10;
        int n = 11;        
        System.out.println(++n == 11 && m == 10);   //  输出结果是false
        System.out.println(n);                      // 输出12,可见不论是f还是t,左边的值都会参与计算输出
        
        int a = 10;
        int b = 11;        
        System.out.println( a == 10  &&  ++b == 11);  //左边true,右边false,最终结果false.
        System.out.println(b);                     // 输出12,左边是true,所以右边会参与计算.
        
        int c = 20;
        int d = 21;        
        System.out.println( c == 21  &&  ++d == 22);  //左边false,右边true,最终结果false.
        System.out.println(d);                     // 输出21,左边是false,所以右边不参与计算.
        
        int e = 20;
        int f = 21;        
        System.out.println( e == 20  &&  f++ == 21);  //左边true,右边false,最终结果false.
        System.out.println(e);                    // 输出20
        System.out.println(f);                    // 输出22,左边是true,所以右边会参与计算.
}
}

3、“|”和“||”的区别同理,||表示:当左边为真,右边不参与运算。

理解:既然左边的已经是true 了也就决定了||是true,不会再继续往右判断了,所以右边不会参与计算

public class Test3 {
    public static void main(String[] args) {
        int a = 0;
        int b = 1;
        System.out.println(a != 0 || ++b == 0);   
        System.out.println(b);                   //左边为false 右边参与计算,输出2
    
     int c = 0; int d = 1; System.out.println(c == 0 || ++d == 0); System.out.println(d); //左边为true 右边不参与计算,输出1
} }

4、在不需要逻辑运算两边都参与运算的时候,尽量使用&&和||


5、异或( ^ )与或( | )的不同之处是:当左右都为true时,结果为false。
理解:异或,追求的是“异”!



猜你喜欢

转载自www.cnblogs.com/wzwzzzzz/p/12452184.html