Java运算符
一、运算符
算术运算符:+,-,*,/,++,--
赋值运算符:=
关系运算符:>,<,>=,<=,==,!=,instanceof
逻辑运算符:&&,||,!
位运算符: &,| ,^(异或),~(取反),>>,<<,>>>(无符号右移,无论正数负数,高位均补0),没有无符号左移(了解!)
条件运算符: (条件表达式)? 表达式1:表达式2
如果条件表达式执行的结果是true,则执行表达式1,否则执行表达式2
扩展赋值运算符:+=,-=,*=,/=
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = -10;
int d = -20;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / (double) b);
System.out.println(a % b);
//关系运算的结果为布尔值
System.out.println(a > b);
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a == b);
// 无long类型参与运算时,非int类型转换为int类型
long e = 1423142;
int f = 123;
short g = 10;
byte h = 1;
System.out.println(e + f + g + h); //Long
System.out.println(f + g + h); //int
System.out.println(g + h); //int
//自增运算符
int i = 1;
int j = i++; //先赋值给j,再自增
int k = ++i; //先自增,再赋值给k
System.out.println(i);
System.out.println(j);
System.out.println(k);
//幂运算
System.out.println("2^3:" + Math.pow(2, 3));
//逻辑运算
boolean b1 = true;
boolean b2 = false;
System.out.println("b1 && b2:" + (b1 && b2));
System.out.println("b1 || b2:" + (b1 || b2));
System.out.println("!(b1 && b2):" + !((b1 && b2)));
//短路运算,与运算前半部分结果为假时,后半部分不判断
int a1 = 6;
boolean bool = (a1 >= 10) && (++a1 < 8);
System.out.println("bool:" + bool);
System.out.println("a1:" + a1);
//位运算
//A = 0011 1100
//B = 0000 1101
// A&B = 0000 1100
// A|B = 0011 1101
// A^B = 0011 0001 异或运算:相同为0,不同为1
// ~B = 1111 0010
// 2*8 = 16 <<左移 *2 >>右移 /2 正数、负数均适用,运算效率高
// 0000 0010 --> 0001 0000
System.out.println(2 << 3);
// 0001 0000 --> 0000 0100
System.out.println(16 >> 2);
int c1 = 10;
int c2 = 20;
System.out.println(c1 += c2);
//字符串连接符 + ,String
System.out.println(" " + c1 + c2); //3020
System.out.println(c1 + c2 + " "); //50
//三元运算符
int score = 70;
String type = score >=60 ? "及格" :"不及格";
System.out.println(type);
}