day13 Java基础——逻辑运算符,位运算符及面试题

1. 逻辑运算符:与,或,非
package operator;
public class Demo07 {
    public static void main(String[] args) {
        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));//逻辑非运算
    }
}
a && b : false
a || b : true
! (a && b) : true
逻辑与运算:两个都为真,结果才为真
 逻辑或运算:两个有一个为真,结果为真
 逻辑非运算:真则变假,假则变真
 短路运算:a&&b中,如果a为假了,结果一定为假,程序判断b是真是假
package operator;
public class Demo07 {
    public static void main(String[] args) {
        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 = 5;
        boolean d = (c<4)&&(c++<4);//逻辑与运算
        System.out.println(d);
        System.out.println(c);
    }
}
a && b : false
a || b : true
! (a && b) : true
false
5
这里c<4必错,故输出d必为false,程序就无需执行判断c++<4的对错了
 所以c没有增加1变成6
2. 位运算符
A = 0011 1100
 B = 0000 1101
A&B = 0000 1100(与)
 A/B = 0011 1101(或)
 A^B = 0011 0001(异或)(相同为0,相异为1)
 ~B = 1111 0010(取反)
面试题:2*8怎么运算最快?
 用位运算
package operator;
public class Demo08 {
    public static void main(String[] args) {
        /*
        <<左移
        >>右移
        0000 0000   0
        0000 0001   1
        0000 0010   2
        0000 0011   3
        0000 0100   4
        0000 1000   8
        0001 0000   16
        往左移动一位,*2
        往右移动一位,\2
        好处:效率极高
        */
        System.out.println(2<<3);
    }
}
16
位运算好处:率极高
 


















