运算符

一元运算符

 

 1 package operation;
 2 //一元运算符:++ -- 自增 自减
 3 public class Demo3 {
 4     public static void main(String[] args) {
 5 
 6         //++在前先自增再赋值,++在后先赋值再自增
 7         int a =3;
 8         int b =a++;//执行完这行代码后,先给b赋值,再自增
 9         //a=a+1
10         System.out.println(a);
11         //a=a+1
12         int c=++a;//执行完这行代码后,先自增,再给c赋值
13 
14         System.out.println(a);
15         System.out.println(b);
16         System.out.println(c);
17 
18         //幂运算 2^3 2*2*2=8   很多运算,我们会使用一些工具类来操作!
19         double pow = Math.pow(2,3);
20         System.out.println(pow);
21     }
22 }
逻辑运算符
 1 package operation;
 2 //逻辑运算符:&&,||,!
 3 public class Demo4 {
 4     public static void main(String[] args) {
 5         //与(and) 或(or) 非(取反)
 6         boolean a =true ;
 7         boolean b =false ;
 8 
 9         System.out.println("a&&b:"+(a&&b));//逻辑与运算:两个变量都为真,结果才为true
10         System.out.println("a||b:"+(a||b));//逻辑或运算:两个变量有一个为真,则结果为true
11         System.out.println("!(a&&b):"+!(a&&b));//如果是真,则变为假;如果是假,则变为真
12 
13         //短路运算
14         int c = 5;
15         boolean d =(c<4)&&(c++<4);//双与运行原则:当左侧为false右侧不参与运算!所以c<4为false,右侧c还是5
16         System.out.println(d);//false
17         System.out.println(c);//5
18 
19     }
20 }
位运算符(效率极高)
 1 package operation;
 2 //位运算符:&,|,^,~,>>,<<,>>>
 3 //效率极高
 4 public class Demo5 {
 5     public static void main(String[] args) {
 6         /*
 7         A = 0011 1100
 8         B = 0000 1101
 9         ---------------------
10         A&B =0000 1100
11         A|B =0011 1101
12         A^B =0011 0001
13         ~B =1111 0010
14 
15         2*8 = 16 2*2*2*2
16         <<  *2
17         >>  /2
18 
19         0000 0000   0
20         0000 0001   1
21         0000 0010   2
22         0000 0011   3
23         0000 0100   4
24         0000 1000   8
25         0001 0000   16
26 
27          */
28         System.out.println(2<<3);//16
29     }
30 }
运算符及字符串连接符
 1 package operation;
 2 //运算符及字符串连接符
 3 public class Demo6 {
 4     public static void main(String[] args) {
 5         int a=10;
 6         int b=20;
 7 
 8         a+=b;//a = a+b
 9         System.out.println(a);//30=10+20
10 
11         a-=b;//a = a-b
12         System.out.println(a);//10=30-20
13 
14         //字符串连接符  + , String 面试题
15         System.out.println(a+b);
16         System.out.println(""+a+b);//不计算直接拼接
17         System.out.println(a+b+"");//先计算在拼接
18 
19     }
20 }
条件运算符(必须掌握)
 1 package operation;
 2 //条件运算符 ? :
 3 public class Demo7 {
 4     public static void main(String[] args) {
 5         // x ? y : z
 6         //如果x==true,则结果为y,否则结果为z
 7 
 8         int score = 80;
 9         String type = score < 60 ? "不及格" :"及格" ;//必须掌握
10         //if
11         System.out.println(type);
12     }
13 
14 }
posted @ 2021-02-04 16:45  奔啵儿灞  阅读(53)  评论(0)    收藏  举报