基础05运算符
java支持如下运算符:优先级()
算数运算符:+,-,×,、,%,++,--
赋值运算符=
关系运算符 >,<,>=,<=,==,!= ,instanceof逻辑运算符:&&.||,!
位运算符:$,|,^,~,>>,<<,>>>
条件运算符? :
扩展赋值运算符:+=,-=,*=,/=
public static void main(String[] args) {
long a=123123123123123L;
int b=123;
short c=10;
byte d=8;
System.out.println(a+b+c+d);//long
System.out.println(b+c+d);//int
System.out.println(c+d);//int 这里也会转换成int
}
public static void main(String[] args) {
int a=10;
int b=20;
int c=21;
System.out.println(c%a);//取余运算
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a==b);
System.out.println(a!=b);
}
自增自减运算
int a = 3;
int b = a++;//执行玩代码后,先给b赋值,再自增
System.out.println(a);
int c = ++a;//先自增,再赋值
System.out.println(a);
System.out.println(b);
System.out.println(c);
4
5
3
5
进程已结束,退出代码0
幂运算
double pow=Math.pow(2,3);
System.out.println(pow);
8.0
进程已结束,退出代码0
这里使用了工具类Math来计算
逻辑运算符
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));//如果是真就变为假,是假就变为真
//短路运算
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):false
false
5
进程已结束,退出代码0
位运算符
/*
* A = 0011 1100
* B = 0000 1101
* A&B = 0000 1100 都是1 才是1
* A|B = 0011 1101 都是0 才是0
* A^B = 0011 0001 相同就是0
* ~B = 1111 0010 全都取反
* 2*8怎么运算最快
* 位运算效率极高
* <<
* >>
* 0000 0000 0
* 0000 0001 1
* 0000 0010 2
* 0000 0100 4
* 0000 1000 8
* 0001 0000 16
*
* */
System.out.println(2<<3);
扩展运算符
int a =10;
int b =20;
a+=b;//就是a=a+b;
a-=b;//就是a=a-b;
字符串连接符
int a =10;
int b =20;
//字符串连接符
System.out.println(""+a+b);
System.out.println(a+b+"");
1020
30
进程已结束,退出代码0
三元运算符
//x?y:z
//如果x==true,结果为y,否则为z
int score=80;
String type=score<60?"不及格":"及格";
System.out.println(type);
及格
进程已结束,退出代码0

浙公网安备 33010602011771号