Day8----------运算符

运算符

  • 算数运算符: + - * / ++ --

  • 赋值运算符 : =

  • 关系运算符: > < >= <= == !=

  • 逻辑运算符: &&(与) ||(或) !(非)

  • 位运算符:| ^ ~ >> << >>>

  • 条件运算符:? :

  • 扩展赋值运算符: += -= *= /=

二元运算符

public class Deme01 {
    public static void main(String[] args) {
        //ctrl+D : 复制当前行到下一行
        //二元运算符
        int b = 10;
        int c = 15;
        int d = 20;


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

         long e = 1212512256L;
         int f = 452;
         short g = 12;
         byte h = 1;

        System.out.println(e+f+g+h); //输出为long类型
        System.out.println(f+g+h); //输出为int 类型
        System.out.println(g+h); //输出为int类型 (在没有long的情况下,输出默认为int)


    }
}

 

自增  自减(++   --);public class Demo02     public static void main(String[] args) {

//++   --   (自增   自减) 一元运算符
        int a = 3;
        int b = a++;  //先赋值,再自增
        //(a=3赋值给b,a自增=4)

        int c = ++a;  //先自增,在赋值
        //(a自增=5,再赋值给c)
        System.out.println(a);
        System.out.println(b);
        System.out.println(c);

         double pow = Math.pow(2,3);  //Math:数学工具类
//pow:求幂运算
System.out.println(pow); } }

 

位运算: &   |   ~(取反)   ^(异或)

 

//位运算  & | ^异或   ~取反
public class Demo04 {
    public static void main(String[] args) {
     /*
     A = 0011 1100;
     B = 0000 1101;
     ------------------
     A&B = 0000 1100
     A|B = 0011 1101
     A^B = 0011 0001
     ~B = 1111 0010

     // 利用位运算效率极高
     <<左移:就是*2
     >>右移:就是/2
     2*8 = 16   2*2*2*2
      */
        System.out.println(2<<3);
    }
}

 

 字符串连接符

//字符串连接符 + ,  String
public class Demo {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        a+=b;  //a=a+b
        a-=b;  //a=a-b
        System.out.println(a);

        System.out.println(a+b);
        System.out.println(""+a+b);
        System.out.println(a+b+"");  //从左到右运算
    }
}

 

 三元运算符

 

//三元运算符  (可以让代码更加精简)
//x ? y : z
//如果x==ture,则结果为y,否则为z
public class Demo05 {
public static void main(String[] args) {
int score = 399;
String type = score>400 ? "考研成功" : "进场打工" ;
System.out.println(type);

}
}

 

posted on 2022-03-25 15:34  三岁学JAVA  阅读(22)  评论(0)    收藏  举报