运算符综述
- 算数运算符:+,-,*,/,%,++,–
- 赋值运算符:=
- 关系运算符:>,<,>=,<=,==,!=
- 逻辑运算符:&&,||,!
- 位运算符:&,|,^,~,>>,<<
- 条件运算符:?,:
- 扩展赋值运算符:+=,-=,*=,/=
1.基本运算符
%为取余运算符
public class Base {
public static void main(String[] args) {
int a =10;
int b =25;
System.out.println(a%b); //取余数
}
}
10
自增++和自减–运算符
public class Base {
public static void main(String[] args) {
int a =3;
int b=a++; //先进行b=a运算,后进行a++运算,a自增后为4
int c=++a; //先进行a自增运算,自增后a=5,后进行c=a运算
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
5
3
5
2.逻辑和位运算符
&& 与运算,|| 或运算,! 非运算
boolean a=true;
boolean b=false;
System.out.println("a&&b:"+a&&b);
System.out.println("a||b:"+a||b);
System.out.println("!(a&&b):"+!(a&&b));
a&&b:false
a||b:true
!(a&&b):true
&与运算,|或运算,^异运算,~非运算
A=0011 1100
B=0000 1101
A&B=0000 1100
A|B=0011 1101
A^B=0011 0001
~B=1111 0010
>>右移运算,<<左移运算
左移相当于*2,右移相当于/2
0000 0001左移得到0000 0010,其他同理
3.其他运算符
+= 运算符, -= 运算符等
a+=b 等同于a=a+b
a-=b 等同于a=a-b
其他同理
三元运算符
public class Base {
public static void main(String[] args) {
//x ? y : z
//如果x==true,则结果为y,否则结果为z
int score=50;
String type =score<60?"不及格":"及格";
System.out.println(type);
}
}
不及格