逻辑运算符&&和||和!

逻辑运算符

逻辑运算符 && , || , !

package operator;
public class demo03 {
    public static void main(String[] args) {
        //逻辑运算符,与(and)、或(or)、非(取反)
        boolean a = true;
        boolean b = false;

        System.out.println("a && b:" + (a && b));//逻辑与运算,两个都为真,结果才为真
        System.out.println("a || b:" + (a || b));//逻辑或运算,有一个为真,结果即为真
        System.out.println("!(a && b):" + !(a && b));//逻辑非运算,如果为真则变为假,如果为假则变为真

        //短路运算
        int c = 2;
        boolean d = (c < 1) && (++c >1);//由于c<1为false,即短路了,不执行&&之后的语句,++c未执行,所以c仍然等于2
        System.out.println(d);//d=false
        System.out.println(c);//c=2

    }
}
posted @ 2023-02-03 15:42  chengh0618  阅读(106)  评论(0编辑  收藏  举报