逻辑操作符中的短路现象

逻辑操作符的短路

  短路:和我们物理中的短路现象是一样的,在这里简单来说就是某段逻辑代码被跳过了,不执行了.

    分析:&&(逻辑与)  两个同时为真时,结果才为真

     ||(逻辑或)  有一个为真时,结果就为真

     !(逻辑非)  取反

        逻辑与中的短路现象:

public static void main(String[] args) {
        //  test1为真    test2为假  test3为真
        boolean b = test1(0) && test2(3) && test3(1) ;
        System.out.println("执行完毕,结果为:"+b);
    }
    
    public static boolean test1(Integer i) {
        System.out.println("执行test1");
        return i < 1;
    }
    public static boolean test2(Integer i) {
        System.out.println("执行test2");
        return i < 2;
    }
    public static boolean test3(Integer i) {
        System.out.println("执行test3");
        return i < 3;
    }

执行结果为:

我们从执行结果中可以看出,test3并没有执行到,这就是逻辑与中的短路现象。

分析:

  例如:boolean类型的A,B,C

     A && B && C

 在这里就必须满足ABC同时为真时才为真。因为代码是从左到右执行的,当代码执行到B时,发现B为false,那么整个表达式就一定为false,那么程序就没有必要再去执行C了。

public static void main(String[] args) {
        
    int i = 0;
    
    boolean b = ++i > 0 && i++ > 1 && i++ > 0;
    
    System.out.println("i为:"+i);
        
    }

输入结果为:

从结果中可以看到:最后的  i++ > 0 并没有执行。

  逻辑或中的短路现象:

public static void main(String[] args) {
        //  test1为假    test2为真   test3为真
        boolean b = test1(3) || test2(1) || test3(2) ;
        System.out.println("执行完毕,结果为:"+b);
    }
    
    public static boolean test1(Integer i) {
        System.out.println("执行test1");
        return i < 1;
    }
    public static boolean test2(Integer i) {
        System.out.println("执行test2");
        return i < 2;
    }
    public static boolean test3(Integer i) {
        System.out.println("执行test3");
        return i < 3;
    }
}

输出结果为:

分析:

  例如:boolean类型的A,B,C

     A || B || C

 在这里只需要ABC中有一个为真,就为真了。如果执行到A时,发现A为真,那么整个结果必然为真,就没有必要再去执行B和C了。(逻辑与和逻辑或的思想是差不多的,当执行完某个表达式时,如果程序能够推测出这整个表达式的结果,那么程序将不会继续执行)

 使用按位运算符就不会出现短路的现象:

public static void main(String[] args) {
        int i = 0;
        boolean b = ++i >0 & i++ >1 & i++ > 2;
     System.out.println(b); System.out.println(i); }

 输入结果为:

 事实上,如果所有的逻辑表达式都有一部分不比计算的话,那么程序将会获得潜在的性能提高。

原文地址:https://www.cnblogs.com/start-21/p/9634371.html