Day04|逻辑运算符、位运算符及三元运算符

本文详细介绍了Java中的逻辑运算符&&、||和!,以及它们的短路特性,并通过示例展示了如何使用。同时,文章还探讨了位运算符,包括&A、|和~的用法,以及如何利用位移运算符快速进行2的幂次运算。最后,提到了三元运算符在条件判断中的应用。
摘要由CSDN通过智能技术生成
逻辑运算符
  • 逻辑运算符 &&, ||, !。
  • && 有一个为假,则为假
  • || 有一个为真,则为真
  • ! 非
package operator;

public class Demo1 {
    public static void main(String[] args) {
        //逻辑运算符 && || !
        /*
        && 有一个为假,则为假
        || 有一个为真,则为真
        !  非
        **/
        //短路运算
        int a=5;
        boolean b=(a<4)&&(++a>5);//只要前边条件错误,后边就不再执行。
        System.out.println(b);
        System.out.println(a);

        boolean c=false;
        boolean d=true;
        System.out.println("c&&d:"+(c&&d));
        System.out.println("c||d:"+(c||d));
        System.out.println("!(c&&d):"+!(c&&d));
    }
}
运行结果:
false
5
c&&d:false
c||d:true
!(c&&d):true
位运算符
    A =0011 1100
    B =0000 1101
    A&B=0000 1100
    A|B=0011 1101
    ~B=1111 0010
    怎样算2*8最快? 位运算
    <<左移 *2
    >>右移 /2
    0000 0000 0
    0000 0001 1
    0000 0010 2
    0000 0011 3
    0000 0100 4
    0000 1000 8
    0001 0000 16

由此可见乘2,相当于左移1位。

package operator;

public class Demo2 {
    public static void main(String[] args) {
        //位运算符
        /*
        A =0011 1100
        B =0000 1101
        A&B=0000 1100
        A|B=0011 1101
        ~B=1111 0010
        面试:怎样算2*8最快? 位运算
        <<左移 *2
        >>右移 /2
        0000 0000 0
        0000 0001 1
        0000 0010 2
        0000 0011 3
        0000 0100 4
        0000 1000 8
        0001 0000 16
        * */
        System.out.println(2<<3);//左移3位 2*2^3
        System.out.println(16>>2);
    }
}
运行结果:
16
4
三元运算符
  • 三元运算符

    x ? y : z 如果x为真,则执行y;否则执行y。

package operator;

public class Demo3 {
    public static void main(String[] args) {
        //字符串连接符 + ,如果有一侧为String类型,则会将另一侧的操作数转换为String类型再连接
        int a = 10;
        int b = 20;
        //面试,""+ 与 +"" 区别
        System.out.println("" + a + b);
        System.out.println(a + b + "");//如果""在后面,前方依旧会进行运算

        //三元运算符
        // x ? y:z  如果x为真,则执行y;否则执行y
        int score = 70;
        String type = score > 60 ? "及格" : "不及格";
        String type1 = score > 80 ? "及格" : "不及格";
        System.out.println(type);
        System.out.println(type1);
    }

}
运行结果:
1020
30
及格
不及格
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值