&&运算符和||运算符的优先级问题 专题

public class SyntaxTest {

    @Test
    public void test() {
        System.out.println(true || true && false);//&&的优化级比||高。所以为true
        System.out.println((true || true) && false);//false
        System.out.println(true || (true && false));//true
    }


}
    @Test
    public void testPriority() {
        /**
         * 用&&连接的两个变量会被当作一个值来看,按从左到右的顺序,
         * 如果&&左边的值为false,则结果已出,&&连接的右边的表达式就不会被执行
         * 这就是短路特性
         * ||运算符的特性:
         * 按顺序进行运算,只要找到一个为真的,就不继续运算,整个结果就返回真
         * &&运算符的特性:
         * 只要找到一个false,就结束
         */
        int flag1 = 1, flag2 = 2;
        LOGGER.info("1、result:{}", checkFalse() && (checkTrue(flag1) || checkTrue(flag2)));//后面两个checkTrue()方法不会被执行
        LOGGER.info("2、result:{}", checkFalse() && checkTrue(flag1) || checkTrue(flag2));//checkTrue(flag1)不会被执行
    }

    private static boolean checkFalse() {
        boolean tmp = false;
        LOGGER.info("I am checkFalse(),I am {}", tmp);
        return tmp;
    }

    private static boolean checkTrue(int flag) {
        boolean tmp = true;
        LOGGER.info("flag:{},I am checkTrue(),I am {}", flag, tmp);
        return tmp;
    }

输出:

16:25:10.357 [main] INFO com.syntax.SyntaxTest - I am checkFalse(),I am false
16:25:10.360 [main] INFO com.syntax.SyntaxTest - 1、result:false
16:25:10.360 [main] INFO com.syntax.SyntaxTest - I am checkFalse(),I am false
16:25:10.360 [main] INFO com.syntax.SyntaxTest - flag:2,I am checkTrue(),I am true
16:25:10.360 [main] INFO com.syntax.SyntaxTest - 2、result:true

依据:根据输出结果可以看出

第二个没有加小括号,在实际执行时前两个checkFalse() && checkTrue()先运算,是一个整体

运算后的结果再与后面的进行||运算

http://ham.iteye.com/blog/198039

单目乘除为关系,逻辑三目后赋值。

单目:单目运算符+ –(负数) ++ -- 等
乘除:算数单目运算符* / % + -
为:位移单目运算符<< >>
关系:关系单目运算符> < >= <= == !=
逻辑:逻辑单目运算符&& || & | ^
三目:三目单目运算符A > B ? X : Y ,其中三目中中的后":"无意义,仅仅为了凑字数
赋值:赋值= 

http://blog.csdn.net/shine0181/article/details/6670023

python中的优先级

运算符示意
not –表示取反运算
and –表示取与运算
or –表示取或运算

运算符优先级
not > and > or

举例如下:

bool_one = False or not True and True
print bool_one
bool_two = False and not True or True
print bool_two
bool_three = True and not (False or False)
print bool_three
bool_four = not not True or False and not True
print bool_four
bool_five = False or not (True and True)
print bool_five


程序输出:

False
True
True
True
False
原文地址:https://www.cnblogs.com/softidea/p/3842529.html