运算符

运算符

算数运算符

+,-,*,/,%

    int a = 10;
    int b = 15;
    int c = 20;
    int d = 25;
    System.out.println(a+b);//加
    System.out.println(a-b);//减
    System.out.println(a*b);//乘
    System.out.println(b%a);//取余
    System.out.println(a/(double) b);//除(默认为int类型,若想显示小数须将其中变量转换为浮点型)
  • 注意点:运算过程中有long类型则输出long类型,其余都为int类型
    long a1 = 1321321322;
    int b1 = 123;
    short c1 = 10;
    byte d1 = 8;

    System.out.println(a1+b1+c1+d1);//long类型
    System.out.println(b1+c1+d1);//int类型
    System.out.println(c1+d1);//int类型

关系运算符

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

    int x = 10;
    int y = 20;
    System.out.println(a>b);
    System.out.println(a<b);
    System.out.println(a==b);
    System.out.println(a!=b);

输出为布尔值true or false

自增自减运算符

++ , --

    int a = 3;

    int b = a++;
    //即 b = a; a = a+1;

    int c = ++a;
    //即 a = a+1; c = a;

逻辑运算符

  • 与,或,非
    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);//并未执行c++,当c<4时短路,跳过c++
    

位运算符

A = 0011 1100

B = 0000 1101

A&B 0000 1100 按位与

A|B 0011 1101 按位或

A^B 0011 0001 按位异或

~B 1111 0010 按位取反

<<左移

'>>右移

  • 位运算效率极高

如2*8,写成2<<3时,运算速度最快

扩展复制运算符

  • a+=b; 即 a = a+b

  • a-=b; 即 a = a-b

三元运算符

  • x ? y : z

    若x == true,结果为y,否则为z

    int score = 80;
    String type = score < 60 ?"不及格":"及格";
    System.out.println(type);//结果为及格

运算符优先级

优先级 运算符 结合性
1 (),[],{} 从左向右
2 ! , + (正), - (负), ~ , ++ , -- 从右向左
3 * , / , % 从左向右
4 +(加) , -(减) 从左向右
5 << , >> , >>> 从左向右
6 < , <= , > , >= , instanceof 从左向右
7 == , != 从左向右
8 & 从左向右
9 ^ 从左向右
10 | 从左向右
11 && 从左向右
12 || 从左向右
13 ?: 从右向左
14 = , += , -= , *= , /= , &= , |= , ^= , ~= , <<= , >>= , >>>= 从右向左
  • 多使用括号

拓展

  1. 很多运算,我们会使用一些工具类来操作

​ 例:幂运算 2^3.

    double pow = Math.pow(2,3);
    System.out.println(pow);
  1. 字符串连接符'+',出现字符串类型时,会将其他类型变成字符串类型
    int a = 10;
    int b = 20;
    System.out.println(a+b);//30
    System.out.println(""+a+b);//变成字符串类型,1020
    System.out.println(a+b+"");//30
posted @ 2021-02-24 13:02  Bry5e  阅读(43)  评论(0)    收藏  举报