java语言支持如下运算符:
-
算数运算符:+ - * / % ++ --
-
赋值运算符:=
-
关系运算符:< > <= >= == != instanceof
-
逻辑运算符:&& || !
-
位运算符:& | ^ ~ << >> >>>(了解)
-
条件运算符:?:
-
拓展赋值运算符:+= -= *= /=
自增自减运算符
-
a++
先赋值再自加
-
++a
先自加再赋值
public class Demo02{
public static void main(String[] args) {
int a = 3;
int b = a++; //a++ a = a + 1 先赋值,再自加
System.out.println(a);
int c = ++a;
System.out.println(a);
System.out.println(b);
System.out.println(c);
//幂运算 2^3 2*2*2
double pow = Math.pow(2, 3);
System.out.println(pow);
}
}
逻辑运算、位运算
-
逻辑运算
package base;
public class Demo02{
public static void main(String[] args) {
boolean a = true;
boolean b = false;
System.out.println("a && b:" + (a&&b)); //逻辑与运算:两个都为真,结果才为true
System.out.println("a || b:" + (a||b)); //逻辑或运算:两个有一个为真,结果为true
System.out.println("!(a && b):" + !(a&&b)); //如果是真变为假,如果是假变为真
System.out.println("========================================================");
//短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);
System.out.println(d);
System.out.println(c);
//c依然为5,说明与运算前面为错时,不进行后面的运算
}
}
-
位运算
package base;
public class Demo02{
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
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16
*/
System.out.println(2<<3);
}
}
扩展赋值运算符
-
a+=b : a = a+b
-
a-=b : a = a-b
public class Demo02{
public static void main(String[] args) {
int a = 10;
int b = 20;
a+=b;
System.out.println(a);
a-=b;
System.out.println(a);
}
}
-
+前为字符串时,后面的直接转为字符串
-
public class Demo02{
public static void main(String[] args) {
int a = 10;
int b = 20;
//字符串连接符 +
System.out.println(a+b);
System.out.println(""+a+b);
System.out.println(a+b+"a");
}
}
30
1020
30a
Process finished with exit code 0
三元运算符
?:
x ? y : z
如果x==true,则结果为y, 否则结果为z
package base;
public class Demo02{
public static void main(String[] args) {
int score = 80;
String type = score < 60 ? "不及格" : "及格"; //必须掌握
System.out.println(type);
}
}
浙公网安备 33010602011771号