Java支持的运算符
-
算数运算符:+,—,*,/,%,++,–;
-
赋值运算符:=;
-
关系运算符:>,<,>=,<=,==(等于),!=(不等于),instanceof;
-
逻辑运算符:&&,||,!;
-
位运算符:&,|,^,~,>>(右移),<<(左移);
-
条件运算符:?,:
-
扩展赋值运算符:+=,-=,*=,/=
自增自减运算符:++,–
很多运算会使用工具类Math使用。
public class Demo04 {
public static void main(String[] args) {
//++自增 --自减 一元运算符
int a = 3;
int b = a++; //执行完这行代码后,先给b赋值,再自增;
int c = ++a; //执行完这行代码前,先自增,再赋值;
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算
double pow = Math.pow(2, 3);
System.out.println(pow);
}
}
5
3
5
8.0
逻辑运算符,位运算符
public class Demo05 {
public static void main(String[] args) {
//逻辑运算符,位运算符
//与,或,非
boolean a = true;
boolean b = false;
System.out.println("a && b:"+(a&&b)); //false
System.out.println("a || b:"+(a||b)); //true
System.out.println("!(a && b):"+!(a && b)); //true
//短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);
System.out.println(d);
System.out.println(c);
}
}
a && b:false
a || b:true
!(a && b):true
false
5
位运算符
//位运算:效率高
public class Demo06 {
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*8 = 16 2*2*2*2
<<左移 : *2
>>右移 : /2
*/
System.out.println(2<<3);
}
}
16
扩展复制运算符
package operator;
public class Demo07 {
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b; //a=a+b
System.out.println(a);
a-=b; //a=a-b
System.out.println(a);
//字符串连接符
System.out.println(a+b);
System.out.println(""+a+b);//字符串在+号前面,则将+号另一侧的操作数转换成String进行连接
System.out.println(a+b+"");//字符串在后面仍进行运算
}
}
30
10
30
1020
30
条件运算符
package operator;
public class Demo08 {
public static void main(String[] args) {
//三元运算符
//x ? y : z
//if x==true ,则结果位y,否则结果为z
int score = 80;
String s = score < 60 ? "不及格" : "及格";
System.out.println(s);
}
}
及格
运算优先级
优先级 | 运算符 | 结合性 |
---|---|---|
1 | ()、[]、{} | 从左向右 |
2 | !、+、-、~、++、– | 从右向左 |
3 | *、/、% | 从左向右 |
4 | +、- | 从左向右 |
5 | «、»、>>> | 从左向右 |
6 | <、<=、>、>=、instanceof | 从左向右 |
7 | ==、!= | 从左向右 |
8 | & | 从左向右 |
9 | ^ | 从左向右 |
10 | | | 从左向右 |
11 | && | 从左向右 |
12 | || | 从左向右 |
13 | ?: | 从右向左 |
14 | =、+=、-=、*=、/=、&=、|=、^=、~=、«=、»=、>>>= | 从右向左 |