基本运算符
Java语言支持如下运算符:
- 算数运算符:+,-,*,/,%(模运算,取余运算),++,–
- 赋值运算符:=
- 关系运算符:>,<,>=,<=,==(等于),!=(不等于),instanceof
- 逻辑运算符:&&(与),||(或),!(非)
- 位运算符:&,|,^,~,>>,<<,>>>(了解!!!)
- 条件运算符:?:
- 扩展赋值运算符:+=,-=,*=,/=
算数运算符
- ++,–
public class demo03 {
public static void main(String[] args) {
// ++ --自增,自减 一元运算符
int a=3;
int b=a++;//执行完这行代码后,先给b赋值,再自增
//a=a+1
System.out.println(a);
//a=a+1
int c=++a;//执行完这行代码前,先自增,再给b赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
4
5
3
5
Process finished with exit code 0
逻辑运算符
public static void main(String[] args) {
//逻辑运算符
//与(and) 或(or) 非(取反)
boolean a=true;
boolean b=false;
System.out.println("a && b:"+(b&&a));//逻辑与运算:两个变量都为真,结果才为true
System.out.println("a || b:"+(a||b));//逻辑或运算:两个变量都有一个为真,则结果才为true
System.out.println("!(a && b):"+!(a&&b));//如果是真,则变为假,如果是假则变为真
a && b:false
a || b:true
!(a && b):true
- 短路运算
/短路运算
int c=5;
boolean d=(c<4)&&(c++<4);//这里c<4是false(短路)所以c++不执行
System.out.println(d);
System.out.println(c);//c=5
}
false
5
位运算符
/*
A=0011 1100
B=0000 1101
----------------
A&B=0000 1100 (上下比较都为1则为1,否则为0)
A|B=0011 1101 (上下比较都为0则为0,否则为1)
A^B=0011 0001 (上下比较都相同则为0,否则为1)
~B=1111 0010 (取反B,与B相反)
*/
<<左移 >>右移
Q:如何快速计算2*8=16
0000 0000 0
0000 0001 1
0000 0010 2
0000 0011 3
0000 0100 4
0000 1000 8
0001 0000 16 //2*3*2=16
System.out.println(2<<3);//<< *2 >> /2
16
扩展赋值运算符
public static void main(String[] args) {
int a=10;
int b=20;
a+=b;//a=a+b
//a-=b;a=a-b
System.out.println(a)
30
//字符串连接符 +,string
System.out.println(""+a+b);//字符串在前面后面直接拼接不计算
System.out.println(a+b+"");//字符串在后面前面依旧运算
三元运算符
public class Demo05 {
//三元运算符
public static void main(String[] args) {
//x?y:z
//如果x==true,则结果为y,否则结果为z
int score=80;
String type =score<60?"不及格":"及格";
//if
System.out.println(type);
}
及格
内容by狂神说2021/1/4