运算符
java 语言支持如下运算符:
- 算术运算符:+ ,- ,*, / , %取模,++自增,--自减
- 赋值运算符 :=
- 关系运算符:>,<,>=,<=,==,!= instanceof
- 逻辑运算符:&&,||,!
- 位运算符:&,|,^,~,>>,<<,>>>
- 条件运算符 ? :
- 拓展赋值运算符:+=,-=,*=,/=
算术运算符 + - * / 二元运算
int a = 10;
int b = 20;
int c = 30;
int d = 40;
System.out.println(a+b);//30
System.out.println(a-b);//-10
System.out.println(a*b);//200
//System.out.println(a/b);//0
System.out.println(a/(double)b);//0.5
取余%
//取余,模运算
int a = 10;
int c = 21;
System.out.println(c%a);//1
自增 一元运算符
++自增
int a = 3;
int b = a++;//先给b赋值 b = a = 3,再自增 a+1
System.out.println(b);//b = 3
System.out.println(a);//a = 4
int c = ++a;//先自增a+1 再赋值 b=a
System.out.println(a);//a = 5
System.out.println(c);//c = 5
自减 一元运算符
--自减
int a = 3;
int b = a--;//先给b赋值 b = a = 3,再自减 a-1
System.out.println(b);//b = 3
System.out.println(a);//a = 2
int c = --a;//先自减a-1 再赋值 b=a
System.out.println(a);//a = 1
System.out.println(c);//c = 1
幂运算
//幂运算 2^3 2*2*2 = 8 3*3 = 9
double pow = Math.pow(2,3);
double pow1 = Math.pow(3,2);
System.out.println(pow);//8.0
System.out.println(pow1);//9.0
逻辑运算
//与(and) 或(or) 非(取反)
boolean a = true;
boolean b = false;
//逻辑与运算:两个变量都为true,输出true,否则输出false
System.out.println("a && b:"+(a && b));//false
//逻辑或运算:两个变量中有一个为true,输出true,两个为false则输出false
System.out.println("a || b:"+(a||b));//true
//如果是true则为false,如果是false则true
System.out.println("!(a && b):"+!(a && b));//true
//短路运算
int c = 5;
boolean d = (c<4)&&(c++<4);//第一个逻辑为false,后面不执行
System.out.println(d);//false
System.out.println(c);//5
boolean e = !(c<4)&&(c++<4);//两个都为false
System.out.println(e);//fasle
System.out.println(c);//6
boolean f = (c<4)||(c++<4);//两个都为true,取反为false
System.out.println(f);//fasle
System.out.println(c);//7
位运算
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 = 16
运算效率高
<< *2
>> /2
0000 0000 0
0000 0001 1
0000 0010 2
0000 0100 4
0000 1000 8
0001 0000 16
System.out.println(2<<3);//16
赋值运算符
int a = 10;
int b = 20;
a+=b;//a = a+b
System.out.println(a);//30
a-=b;//a = a-b
System.out.println(a);//10
字符串连接题
//字符串连接符 + ,String
//遇到为字符串,后面转化为字符串
System.out.println(""+a+b);//1020
System.out.println(a+b+"");//30
System.out.println(a+b+""+a+b);//301020
三元运算符
//x ? y : z
//如果x == true,则结果为true,否则结果为z
int score = 80;
String type = score < 60 ? "不及格" : "及格";
System.out.println(type);//及格
优先级
//优先级 先算()后*/+-
int a = 1;
int b = 1;
int c = 1;
int d = 1;
System.out.println((a+b)*c/d-a);//1