Java ——运算符
本节重点思维导图
递增递减
前缀自增自减法(++a,--a): 先进行自增、减运算,再进行表达式运算
后缀自增自减法(a++,a--): 先进行表达式运算,再进行自增、减运算
例【1】:
int a = 2; int b = ++a; System.out.println("++a = " + b); a=2; int c = --a; System.out.println("--a = " + c); a=2; int x = a--; System.out.println("a-- = " + x); a=2; int y = a++; System.out.println("a++ = " + y);
结果: 3 1 2 2
例【2】:
int a = 2; if(a++ == 2) System.out.println("a++ = 2"); a = 2; if(a-- == 2) System.out.println("a-- = 2"); a = 2; if(--a == 1) System.out.println("--a == 1"); a = 2; if(++a == 3) System.out.println("++a == 3");
结果:
a++ = 2
a-- = 2
--a == 1
++a == 3
赋值运算符
int a =3; a+=3; a = a+3; a-=4; a = a-4; a*=5 a= a*5; a/= 3 a= a/3; a%b a%=b a = a%b;
关系运算符
结果是boolean类型
>、>=、<、<=、==、!=
int a = 47; int b = 7; boolean res1 = a>b; //if a > b,res1 = true System.out.println(res1); boolean res2 = a == b; //if a == b,res2 = true System.out.println(res2); //结果是true false
逻辑运算符
&& 与 ||或 !非
boolean b1 = true; boolean b2 = false; boolean b = b1 || b2; System.out.println(b); System.out.println(!b2);
&& || 与& |的区别,双的有短路作用:
短路:当结果一定成立时,就不再计算后面的了
int a = 2; boolean b1 = a++ == 2; System.out.println(b1); System.out.println(a); boolean b2 = --a != 2; System.out.println(b2); System.out.println(a); System.out.println("--------------------"); boolean res = b1 && b2; System.out.println(res); System.out.println(a);
结果:
true 3 false 2 -------------------- false 2
^异或运算符
字符能够进行异或运算
一个字符进行两次异或运算就会回到原来的值
char c ='a'; System.out.println(c^'0'); System.out.println((char)(c^'0')); System.out.println(c^'0'^'0'); System.out.println((char)(c^'0'^'0'));
结果:
81 Q 97 a
三目运算符
int a = 10; int b = 15; String res = a>b ? "max is a":"max is b"; System.out.println(res);
instanceof 运算符
移位运算符
<<:向左移位,相当于变大为原来的2的多少次幂
>>:向右移位,相当于变小为原来的2的多少次幂
可以快速地计算2的多少次方
int a = 1<<3; //1*2^3 System.out.println(a); a = 4<<6; //4*2^6=2^8 System.out.println(a); a = 256>>3; System.out.println(a);
8
256
32
instanceof 额外补充
1.【总结在上方思维导图中】
2.