Java Basics Part 8/20 - Basic Operators
目录
Java 提供了丰富的操作运算符。可以分成以下几组:
- 算术运算符
- 关系运算符
- 位运算符
- 逻辑运算符
- 赋值运算符
- 其他运算符
算术运算符
算术运算符用在数学表达式中:
假设 A 的值是 10, B 的值 是 20
SR.NO | Operator and Example |
---|---|
1 |
|
2 |
|
3 |
|
4 | / 除: B / A =>2 |
5 | % 取模: B % A => 0 |
6 | ++ 自加1: B++ => 21 |
7 | -- 自减1: B-- => 19 |
关系运算符
同样,假设 A 是 10,B 是 20
SR.NO | Operator and Description |
---|---|
1 | == 等于: A== B false |
2 | != 不等于: A != B true |
3 | > 大于: A > B false |
4 | < 小于: A < B true |
5 | >= 大于等于: A >= B false |
6 | <= 小于等于: A <= B true |
位运算符
Java 定义了很多位运算符,可以用在 int, long,short,char 和 byte 上。
位运算符操作的是 bit。假设 a = 60; b = 13.
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
同样,假设整形 A 是 60, B 是 13
SR.NO | Operator and Description |
---|---|
1 | & 位与: A & B => 12(0000 1100) |
2 | | 位或: A |
3 | ^ 位异或: A ^ B => 49(0011 0001) |
4 | ~ 位补码: ~A => -61(1100 0011) |
5 | << 左移:A << 2 => 240(1111 0000) |
6 | >> 右移: A >> 2 => 15(1111) |
7 | >>> 无符号右移: A >>> 2 => 15(0000 1111) |
逻辑运算符
假设 A 为 true, B 为 false
Operator | Description |
---|---|
1 | && 逻辑与: A && B => false |
2 | || 逻辑或: A || B => true |
3 | ! 逻辑非: !(A&&B) => true |
赋值运算符
SR.NO | Operator and Description |
---|---|
1 | = |
2 | += |
3 | -= |
4 | *= |
5 | /= |
6 | %= |
7 | <<= |
8 | >>= |
9 | &= |
10 | ^= |
11 | |= |
其他运算符
条件运算符(?:)
variable x = (expression) ? value if true : value if false
举例:
public class Test {
public static void main(String args[]){
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
// output
Value of b is : 30
Value of b is : 20
instanceof 操作符
这个操作符仅用于对象的引用变量。它会检查出一个对象是否是一个特定的类型。
( Object reference variable ) instanceof (class/interface type)
如果 对象 是 类 的实例,那么结果就是 true,否则就是 false
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
// output
true
操作符优先级
Category | Operator | Associativity |
---|---|---|
Postfix | () [] . (dot operator) | Left to right |
Unary | ++ - - ! ~ | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | >> >>> << | Left to right |
Relational | > >= < <= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %= >>= <<= &= ^= | = |