运算符
Java语言支持如下运算符:
算术运算符:+,-,*,/,%,++,--
赋值运算符:=
关系运算符:>,<,>=,<=,==,!=,instanceof
public static void main(String[] args) {
//二元运算符
int a = 10;
int b = 20;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println((float) a / b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a == b);
System.out.println("-------分---------割--------------线-------");
//若运算中有long类型数值,则结果为long,若没有,则为int
long c = 12312321231232L;
int d = 123;
short e = 10;
byte f = 8;
System.out.println(c+d+e+f); //long
System.out.println(d+e+f); //int
System.out.println(e+f); //int
}
public static void main(String[] args) {
// ++:自增 --:自减
int a = 3;
int b = a++; //先给b赋值,再自增
System.out.println(a); // 4
System.out.println(b); // 3
int c = ++a; //先自增,再给c赋值
System.out.println(a); // 5
System.out.println(c); // 5
}
逻辑运算符:&&,||,!
public class Study{
public static void main(String[] args) {
//&& : and || : or ! : not
boolean a = true;
boolean b = false;
System.out.println(a && b); //false
System.out.println(a || b); //true
System.out.println(!(a && b)); //true
//短路运算
int c = 5;
boolean d = (c<4)&&(c++<10);
//检测到c<4时便直接输出false,故c++没有被执行
System.out.println(d);
System.out.println(c);
}
位运算符:&,|,^,~,>>,<<,>>>
public static void main(String[] args) {
/*
A = 0011 1100
B = 0000 1101
A&B = 0000 1100
A|B = 0011 1101
A^B = 00110001
~B = 1111 0010
*/
// 面试题,最快方式算出2*8
System.out.println(2<<3);
/*
原理:
0000 0001 1
0000 0010 2
0000 0100 4
0000 1000 8
0001 0000 16
故<< = *2
>> = /2
*/
}
条件运算符:?,:
//三元运算符
// x ? y : z //如果x==true,则结果为Y,否则结果为z
int score = 80;
String type = score <60 ? "不及格" : "及格";
System.out.println(type);
扩展赋值运算符:+=,-=,*=,/=
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a += b); //a += b 等同 a = a+b
}