运算符
算术运算符:+,-,*,/,%,++,- -
赋值运算符:=
关系运算符:>,<,>=,<=,==,!=instanceof
逻辑运算符:&&,||,!
位运算符:&,|,^,~,>>,<<,>>>
条件运算符:?:
扩展赋值运算符:+=,-=,*=,/=
加减乘除(+,-,*,/):
//二元运算符
int a = 10;
int b = 20;
System.out.println(a+b);//30
System.out.println(a-b);//-10
System.out.println(a*b);//200
System.out.println(a/b);//0
long a = 123123123123123L;
int b = 123;
short c = 10;
byte d = 8;
System.out.println(a+b+c+d);//123123123123264 Long
System.out.println(b+c+d);//141 Int
System.out.println(c+d);//18 Int
大于、小于、等于、不等于(>,<,==,!=):
int a = 10;
int b = 20;
System.out.println(a>b);//false
System.out.println(a<b);//true
System.out.println(a==b);//false
System.out.println(a!=b);//true
取余、模运算:
int a =10;
int b = 20;
int c = 22;
System.out.println(c%a);// 22 / 10 =2...2
自增、自减 (++,–)(一元运算符):
int a = 3;
int b = a++;
int c = ++a;
System.out.println(a);//5
System.out.println(b);//3
System.out.println(c);//5
//幂运算 很多运算,我们会使用一些工具类来操作
double pow = Math.pow(3,2); //3^2=9
System.out.println(pow);//9
与(and) 或(or) 非(取反):
boolean a = true;
boolean b = false;
System.outprintln("a && b:" + (a&&b));//与:两个变量都为真,结果才为true
System.outprintln("a || b:" + (a||b));//或:两个变量有一个为真,则结果为true
System.outprintln("!(a&&b):" + !(a&&b));//如果是真,则变为假,如果是假,则变为真
//短路运算
int c = 5;
boolean d = (c < 4) && (c++ < 4);
System.out.println(d);//false
System.out.println(c);//5
面试题(与、或、非、取反):
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
<< *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);//16
赋值运算符:
int a = 10;
int b = 20;
a+=b;//a= a+b
a-=b;//a=a-b
a/=b;//a=a/b
System.out.println(a);
System.out.println("" + a + b);//1020
System.out.println(a+b+"");//30
三元运算符:
int score = 50;
//x?y:z
//如果x==true,则结果为y,否则结果为z
String type = score < 60?"及格":"不及格";
System.out.println(type);//不及格