逻辑运算符

逻辑运算符分为以下几个:

  &

    两边为true则为true,否则为false

  |

    一边为true则为true

  !

    true则得false,false则得true

  ^

    两边不同则为true,两边相同则为false

  &&

    短路&,结果与&的一致,区别在于如果左边能得到结果,则右边不执行

  ||

    短路或,结果与|一致,区别在于如果左边能得到结果,则右边不执行

例子:

public class TestOperator {
    public static void main(String[] args) {
        /*
            & 两边为真则为真
            | 一边为真则为真
            ! 真则为假
            ^ 两边同则为假,不同则为真
        */
        System.out.println(true & false);
        System.out.println(true & true);
        System.out.println(false & true);
        System.out.println(true | false);
        System.out.println(true | true);
        System.out.println(false | true);
        System.out.println(false | false);
        System.out.println(!true);
        System.out.println(!false);
        System.out.println(true ^ false);
        System.out.println(true ^ true);
        System.out.println(false ^ true);
        System.out.println(false ^ false);
        
        /*
            && ||
            运算结果与单&或单|没有区别
            区别在于短路现象
            使用的时候尽量使用&&和||
        */
        
        System.out.println(true && false);
        System.out.println(true && true);
        System.out.println(false && true);
        System.out.println(true || false);
        System.out.println(true || true);
        System.out.println(false || true);
        System.out.println(false || false);
        
        int i = 10;
        if(i>10 && i++ <20){
            System.out.println(" i在10和20之间");
        }
        System.out.println(" i=" + i);
        
        int i2 = 10;
        if(i2>10 & i2++ <20){
            System.out.println(" i2在10和20之间");
        }
        System.out.println(" i2=" + i2);
        
        
    }
}
原文地址:https://www.cnblogs.com/aigeileshei/p/10554014.html