运算符

运算符

算数运算符

+,-,*,/,%,++,--

package operator;

public class Demo01 {
    public static void main(String[] args) {
        int a=10;
        int b=20;
        int c=30;
        int d=40;

        System.out.println(a + b);
        System.out.println(a - b);
        System.out.println(a * b);
        System.out.println((float)a/b);
    }
}

赋值运算符

=

关系运算符

<, >, <=, >=, ==, !=

逻辑运算符

&&,||,! 与或非

package operator;

public class Demo02 {
    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 < 5) && (c++ > 5);  //与运算:前一步false,后一步运算不进行
        System.out.println("d:" + d);
        System.out.println("c:" + c);


        int e = 3;
        System.out.println(e);
        System.out.println(e++);    //3   先输出,再自增
        //e=e+1
        //e=e+1
        System.out.println(++e);    //5   先自增,在输出

    }
}

位运算符(了解)

&, |, ^, ~, >>, <<, >>>

package operator;

public class Demo03 {
    public static void main(String[] args) {
        //位运算
        /*
        A  =  0011 1100
        B  =  0000 1101
        --------------------
        A&B=  0000 1100  与
        A|B=  0011 1101  或
        A^B=  0011 0001  异或    相同为0,不同为1
        ~A =  1100 0011  非
        ~B =  1111 0010  非

         <<  左移  *2
         >>  右移  /2
         -------------------
         0000 0000   0
         0000 0001   1
         0000 0010   2
         0000 0011   3

         */

        System.out.println(2<<3);         //   2*2*2*2
        System.out.println(16>>3);        //   16/2/2/2


    }
}

条件运算符(重要)

?:

package operator;
// 三元运算符
public class Demo05 {
    public static void main(String[] args) {

        // x ? y : z
        // 若x为true,则输出x,反之输出y

        int score=55;
        String type=score>60?"及格":"不及格";  //必须掌握!!!     if
        System.out.println(type);

    }
}

扩展赋值运算符

+=, -=, *=, /=

package operator;

public class Demo04 {
    public static void main(String[] args) {

        int a = 10;
        int b = 20;
        //扩展赋值运算符  +=   -=   *=   /=
        //  a+=b   a=a+b
        //  a-=b   a=a-b
        //  a*=b   a=a*b
        //  a/=b   a=a/b

        //字符串连接符    +
        System.out.println(""+a+b);    //1020  "":转为字符串类型
        System.out.println(a+b+"");    //30
        System.out.println(""+(a+b));  //30

    }
}

posted @ 2020-10-30 20:12  o叉烧包  阅读(58)  评论(0)    收藏  举报