三、Operators 运算符
Assignment Operators(赋值运算符)
= += -= %= *= /= <<= >>= >>>= &= ^= |=
public class ByteDemo {
public static void main(String[] args) {
byte b1=2;
byte b2=3;
b1=(byte)(b1+b2); //加法,转int
b1+=b2; //赋值,不转int
}
}
b1+=b2;与b1=b1+b2;是否完全等价?
答案是否定的。byte类型参数与运算时要先转换为int型,因此要进行强制类型转换。(可以把“b11+=b2;”看做是对“b1=(byte)(b1+b2);”的优化!)
Comparison Operators(比较运算符)
> >= < <= instanceof
Equality Operators(相同运算符)
== !=
Arithmetic Operators(算术运算符)
+ - * / %
Shift Operators(移位运算符)
>> << >>>
public class Test {
public static void main(String[] args) {
String s1 = Integer.toBinaryString(-1);
System.out.println(s1); // 11111111,11111111,11111111,11111111
int i1 = Integer.valueOf("1111111100000000", 2);
System.out.println(i1); // 65280
int i2 = i1 >> 1;
System.out.println(Integer.toBinaryString(i2)); // 01111111,10000000
int i3 = i1 << 1;
System.out.println(Integer.toBinaryString(i3)); // 00000001,11111110,00000000
int i4 = i1 >>> 1;
System.out.println(Integer.toBinaryString(i4)); // 01111111,10000000
// 零位扩展和符号位扩展
System.out.println(Integer.toBinaryString(-1 >> 1)); // 11111111,11111111,11111111,11111111
// -1
System.out.println(Integer.toBinaryString(-1 >>> 1)); // 01111111,11111111,11111111,11111111
// 2147483647
}
}
Bitwise Operators(位运算符)
& | ^(按位异或) ~(按位取反)
Logic Operators(逻辑运算符)
&& & || | !
Conditional Operators(条件运算符)
?:
public class Test {
public static void main(String[] args) {
boolean b = true;
int i = b ? 1 : 2;
System.out.println(i); // 1
}
}
Other operators
++ --
public class TestAction { public static void main(String[] args) {
int i = 2;
System.out.println(i++); // 2
System.out.println(i); // 3
int a = i++ + i; // 3+4=7
System.out.println(a);
int b = i++ + ++i; // 3+5=10
i++;
System.out.println(b);
System.out.println(i); // 7
for (int j = 0; j < 1000; j++) {
i = i++;
}
System.out.println(i); // 7
}
}