逻辑运算符,三元运算符

简单运算符

在这里插入图片描述

自增自减运算符

 public static void main(String[] args) {
    long a=123123123123L;
    int b=123;
    short c=10;
    byte d=8;
        System.out.println(a+b+c+d);//long
        System.out.println(b+c+d);//int
        System.out.println(c+d);//int

注意:计算时如果有long或者double,计算出来为他们的类型,如果没有,计算结果默认为int类型

 //++ -- 自增,自减,一元运算符
        int a1=3;
        int b1=a1++;//a1=a1+1,执行完这行代码,先给a1赋值,再自增
        System.out.println(a1);
        //a1=a1+1
        int c1=++a1;//执行完这行代码前,先自增,再给b1赋值
        System.out.println(a1);
        System.out.println(b1);
        System.out.println(c1);

        //幂运算  2^3 =8  很多运算,使用一些工具类来操作
        double pow=Math.pow(2,3);
        System.out.println(pow);

逻辑运算符

 //与(and) 或(or) 非(取反)
        boolean A=true;
        boolean B=false;
        System.out.println("A && B:"+(A&&B));//false
        System.out.println("A || B:"+(A || B));//true
        System.out.println("!(A&&B):"+!(A&&B));//true

注意:

&& 逻辑与运算,两个变量都为真,结果为true
|| 逻辑或运算,两个变量有一个为真,则结果才为true
! 如果是真,变量为假,如果是假则为真

短路运算

  int C=5;
        boolean D=(C<4)&&(C++<4);
        System.out.println(D);//false
        System.out.println(C);//5,C<4为假,则后面的不进行运算为5

位运算

 /*
        A =0011 1100
        B =0000 1101
        ----------------------------
        A&B=0000 1100,
        A|B=0011 1101,
        A^B=0011 0001,相同为0,不同为1
        ~B=1111 0010

        << 左移   相当于*2
        >> 右移   相当于/2
        0000 0000    0
        0000 0001    1
        0000 0010    2
        0000 0011    3
        0000 0100    4
        0000 0101    5
        0000 1000    8
        0001 0000    16

*/

        System.out.println(2<<3);//1向左移动三位,输出结果为16.


连接运算符


        int a=10;
        int b=20;
        a+=b;//相当于a=a+b
        a-=b;//相当于a=a-b
        System.out.println(a);//10

        //字符串连接符   +,String
        System.out.println(""+a+b);//1020,此时+为连接符,前面如果有字符串,则不计算
        System.out.println(a+b+"");//30,先计算

三元运算符

//  三元运算符
        //x ? y : z
        //如果x==true,则结果为y,否则结果为z

        int score=80;
        String type=score<60?"不及格":"及格";
        System.out.println(type);//及格
发布了24 篇原创文章 · 获赞 5 · 访问量 548

猜你喜欢

转载自blog.csdn.net/weixin_46178009/article/details/104329010