前言

运算符是编程语言中执行特定数学、关系或逻辑运算的符号。Java提供了丰富的运算符集合,从基本的算术运算到复杂的位运算,这些运算符是构建程序逻辑的基础工具。本文将详细介绍Java中的各类运算符,包括它们的用法、优先级和在实际编程中的应用场景。

Java运算符分类概览

Java运算符可以根据功能分为多个类别,每个类别都有其特定的用途和应用场景:

mindmap
  root((Java运算符))
    算术运算符
      +加法
      -减法
      *乘法
      /除法
      %取模
      ++自增
      --自减
    赋值运算符
      =简单赋值
      +=加法赋值
      -=减法赋值
      *=乘法赋值
      /=除法赋值
      %=取模赋值
    比较运算符
      ==等于
      !=不等于
      >大于
      <小于
      >=大于等于
      <=小于等于
    逻辑运算符
      &&逻辑与
      ||逻辑或
      !逻辑非
    位运算符
      &按位与
      |按位或
      ^按位异或
      ~按位取反
      <<左移
      >>右移
      >>>无符号右移
    三元运算符
      ?:条件表达式
    其他运算符
      instanceof类型检查
      []数组下标
      ()方法调用

算术运算符

算术运算符用于执行基本的数学运算,是最常用的运算符类别。

基本算术运算符

加法运算符 (+)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class ArithmeticOperators {
public static void demonstrateAddition() {
// 数值加法
int a = 10;
int b = 20;
int sum = a + b; // 30

// 浮点数加法
double x = 3.14;
double y = 2.86;
double result = x + y; // 6.0

// 字符串连接
String str1 = "Hello";
String str2 = "World";
String message = str1 + " " + str2; // "Hello World"

// 混合类型运算
String info = "Result: " + sum; // "Result: 30"

System.out.println("整数相加: " + sum);
System.out.println("浮点数相加: " + result);
System.out.println("字符串连接: " + message);
System.out.println("混合连接: " + info);
}
}

减法运算符 (-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void demonstrateSubtraction() {
int minuend = 100; // 被减数
int subtrahend = 30; // 减数
int difference = minuend - subtrahend; // 70

// 负数表示
int negative = -difference; // -70

// 浮点数减法精度问题
double d1 = 1.0;
double d2 = 0.9;
double diff = d1 - d2; // 可能不是期望的0.1

System.out.println("基本减法: " + difference);
System.out.println("负数: " + negative);
System.out.println("浮点减法: " + diff);
}

乘法运算符 (*)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void demonstrateMultiplication() {
// 基本乘法
int factor1 = 12;
int factor2 = 8;
int product = factor1 * factor2; // 96

// 科学计算
double radius = 5.0;
double area = Math.PI * radius * radius; // 圆面积

// 溢出问题
int largeNum1 = Integer.MAX_VALUE;
int largeNum2 = 2;
int overflow = largeNum1 * largeNum2; // 溢出,结果为负数

// 使用long避免溢出
long safeProduct = (long) largeNum1 * largeNum2;

System.out.println("基本乘法: " + product);
System.out.println("圆面积: " + area);
System.out.println("溢出结果: " + overflow);
System.out.println("安全乘法: " + safeProduct);
}

除法运算符 (/)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public void demonstrateDivision() {
// 整数除法(截断小数部分)
int dividend = 17;
int divisor = 3;
int quotient = dividend / divisor; // 5,小数部分被截断

// 浮点数除法
double preciseResult = (double) dividend / divisor; // 5.666...

// 除零异常处理
try {
int result = dividend / 0; // 抛出ArithmeticException
} catch (ArithmeticException e) {
System.out.println("整数除零异常: " + e.getMessage());
}

// 浮点数除零
double floatDivision = 1.0 / 0.0; // Infinity
double nanResult = 0.0 / 0.0; // NaN

System.out.println("整数除法: " + quotient);
System.out.println("精确除法: " + preciseResult);
System.out.println("浮点除零: " + floatDivision);
System.out.println("NaN结果: " + nanResult);
}

取模运算符 (%)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public void demonstrateModulo() {
// 基本取模运算
int dividend = 17;
int divisor = 3;
int remainder = dividend % divisor; // 2

// 判断奇偶数
boolean isEven = (dividend % 2 == 0);
boolean isOdd = (dividend % 2 != 0);

// 循环数组索引
int[] array = {1, 2, 3, 4, 5};
int index = 7;
int circularIndex = index % array.length; // 2

// 浮点数取模
double floatMod = 5.5 % 2.0; // 1.5

// 负数取模
int negativeMod1 = -17 % 3; // -2
int negativeMod2 = 17 % -3; // 2
int negativeMod3 = -17 % -3; // -2

System.out.println("基本取模: " + remainder);
System.out.println("是否为偶数: " + isEven);
System.out.println("循环索引: " + circularIndex);
System.out.println("浮点取模: " + floatMod);
System.out.println("负数取模: " + negativeMod1);
}

自增自减运算符

graph TD
    A[自增自减运算符] --> B[前缀形式]
    A --> C[后缀形式]
    
    B --> D[++i 先增后用]
    B --> E[--i 先减后用]
    
    C --> F[i++ 先用后增]
    C --> G[i-- 先用后减]
    
    D --> H[返回增加后的值]
    E --> I[返回减少后的值]
    F --> J[返回原值]
    G --> K[返回原值]

前缀和后缀的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class IncrementDecrementDemo {
public static void demonstrateIncrement() {
// 前缀自增:先增加,后返回值
int a = 5;
int preIncrement = ++a; // a变为6,preIncrement为6
System.out.println("前缀自增: a=" + a + ", preIncrement=" + preIncrement);

// 后缀自增:先返回值,后增加
int b = 5;
int postIncrement = b++; // postIncrement为5,b变为6
System.out.println("后缀自增: b=" + b + ", postIncrement=" + postIncrement);

// 在循环中的应用
System.out.println("前缀自增循环:");
for (int i = 0; i < 3; ++i) {
System.out.print(i + " "); // 0 1 2
}

System.out.println("\n后缀自增循环:");
for (int i = 0; i < 3; i++) {
System.out.print(i + " "); // 0 1 2
}

// 复杂表达式中的区别
int x = 10;
int result1 = x++ + ++x; // (10) + (12) = 22, x最终为12

int y = 10;
int result2 = ++y + y++; // (11) + (11) = 22, y最终为12

System.out.println("\n复杂表达式1: " + result1);
System.out.println("复杂表达式2: " + result2);
}
}

赋值运算符

赋值运算符用于给变量赋值,Java提供了多种赋值运算符来简化代码。

简单赋值运算符 (=)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class AssignmentOperators {
public void demonstrateSimpleAssignment() {
// 基本赋值
int number = 42;
String text = "Hello Java";
boolean flag = true;

// 链式赋值
int a, b, c;
a = b = c = 10; // 从右到左执行:c=10, b=c, a=b

// 对象引用赋值
String str1 = "Original";
String str2 = str1; // str2指向同一个字符串对象

System.out.println("链式赋值: a=" + a + ", b=" + b + ", c=" + c);
}
}

复合赋值运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public void demonstrateCompoundAssignment() {
// 算术复合赋值
int value = 10;
value += 5; // 等价于 value = value + 5,结果为15
value -= 3; // 等价于 value = value - 3,结果为12
value *= 2; // 等价于 value = value * 2,结果为24
value /= 4; // 等价于 value = value / 4,结果为6
value %= 5; // 等价于 value = value % 5,结果为1

// 字符串复合赋值
String message = "Hello";
message += " World"; // "Hello World"
message += "!"; // "Hello World!"

// 类型转换的自动处理
byte b = 10;
b += 1; // 编译器自动处理类型转换,等价于 b = (byte)(b + 1)

// 位运算复合赋值
int flags = 0b1010;
flags &= 0b1100; // 按位与赋值,结果为0b1000
flags |= 0b0011; // 按位或赋值,结果为0b1011
flags ^= 0b1111; // 按位异或赋值,结果为0b0100

System.out.println("最终值: " + value);
System.out.println("字符串: " + message);
System.out.println("位运算结果: " + Integer.toBinaryString(flags));
}

比较运算符

比较运算符用于比较两个值,返回boolean类型的结果。

graph LR
    A[比较运算符] --> B[相等性比较]
    A --> C[关系比较]
    
    B --> D[== 等于]
    B --> E[!= 不等于]
    
    C --> F[> 大于]
    C --> G[< 小于]
    C --> H[>= 大于等于]
    C --> I[<= 小于等于]

数值比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class ComparisonOperators {
public void demonstrateNumericComparison() {
int a = 10;
int b = 20;
int c = 10;

// 基本比较
boolean equal = (a == c); // true
boolean notEqual = (a != b); // true
boolean greater = (b > a); // true
boolean less = (a < b); // true
boolean greaterEqual = (a >= c); // true
boolean lessEqual = (a <= b); // true

// 浮点数比较的精度问题
double d1 = 0.1 + 0.2;
double d2 = 0.3;
boolean floatEqual = (d1 == d2); // false!精度问题

// 正确的浮点数比较方法
final double EPSILON = 1e-10;
boolean correctFloatEqual = Math.abs(d1 - d2) < EPSILON; // true

System.out.println("整数比较: " + equal);
System.out.println("浮点数直接比较: " + floatEqual);
System.out.println("浮点数正确比较: " + correctFloatEqual);
}
}

对象比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public void demonstrateObjectComparison() {
// 字符串比较
String str1 = new String("Hello");
String str2 = new String("Hello");
String str3 = "Hello";
String str4 = "Hello";

// 引用比较 vs 内容比较
boolean referenceEqual1 = (str1 == str2); // false,不同对象
boolean referenceEqual2 = (str3 == str4); // true,字符串池
boolean contentEqual = str1.equals(str2); // true,内容相同

// null比较
String nullStr = null;
boolean nullComparison = (nullStr == null); // true
// boolean errorComparison = nullStr.equals("test"); // NullPointerException
boolean safeComparison = Objects.equals(nullStr, "test"); // false

// 数组比较
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
boolean arrayRefEqual = (array1 == array2); // false
boolean arrayContentEqual = Arrays.equals(array1, array2); // true

System.out.println("字符串引用比较: " + referenceEqual1);
System.out.println("字符串内容比较: " + contentEqual);
System.out.println("数组内容比较: " + arrayContentEqual);
}

逻辑运算符

逻辑运算符用于组合或修改布尔表达式,支持短路求值机制。

graph TD
    A[逻辑运算符] --> B[逻辑与 &&]
    A --> C[逻辑或 ||]
    A --> D[逻辑非 !]
    
    B --> E[短路求值
第一个为false时
不计算第二个] C --> F[短路求值
第一个为true时
不计算第二个] D --> G[单目运算符
取反布尔值]

逻辑与运算符 (&&)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class LogicalOperators {
public void demonstrateLogicalAnd() {
// 基本逻辑与
boolean condition1 = true;
boolean condition2 = false;
boolean result = condition1 && condition2; // false

// 短路求值演示
int x = 5;
int y = 0;

// 安全的除法检查
if (y != 0 && x / y > 2) { // y != 0为false,不会执行x/y
System.out.println("除法结果大于2");
}

// 复杂条件判断
String str = "Hello";
if (str != null && str.length() > 3 && str.startsWith("H")) {
System.out.println("字符串满足所有条件");
}

// 方法调用的短路
if (isValidUser("admin") && hasPermission("admin", "write")) {
System.out.println("用户有写权限");
}
}

private boolean isValidUser(String username) {
System.out.println("检查用户: " + username);
return "admin".equals(username);
}

private boolean hasPermission(String user, String permission) {
System.out.println("检查权限: " + permission);
return true;
}
}

逻辑或运算符 (||)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public void demonstrateLogicalOr() {
// 基本逻辑或
boolean condition1 = false;
boolean condition2 = true;
boolean result = condition1 || condition2; // true

// 默认值设置
String input = null;
String value = (input != null) ? input : "default";
// 或者使用逻辑或的短路特性
boolean hasValue = (input != null) || setDefaultValue();

// 多条件检查
int score = 85;
if (score >= 90 || score >= 80 && hasExtraCredit()) {
System.out.println("成绩优秀");
}

// 异常处理中的应用
try {
processData();
} catch (IllegalArgumentException | NullPointerException e) {
System.out.println("参数错误: " + e.getMessage());
}
}

private boolean setDefaultValue() {
System.out.println("设置默认值");
return true;
}

private boolean hasExtraCredit() {
return false;
}

private void processData() {
// 处理数据的方法
}

逻辑非运算符 (!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public void demonstrateLogicalNot() {
// 基本逻辑非
boolean isValid = true;
boolean isInvalid = !isValid; // false

// 双重否定
boolean original = false;
boolean doubleNot = !!original; // false,等价于original

// 条件取反
List<String> list = Arrays.asList("a", "b", "c");
if (!list.isEmpty()) {
System.out.println("列表不为空");
}

// 复杂表达式中的否定
int age = 20;
boolean isAdult = age >= 18;
if (!(age < 18)) { // 等价于 age >= 18
System.out.println("已成年");
}

// De Morgan定律应用
boolean a = true, b = false;
boolean result1 = !(a && b); // true
boolean result2 = (!a) || (!b); // true,与result1等价
boolean result3 = !(a || b); // false
boolean result4 = (!a) && (!b); // false,与result3等价

System.out.println("De Morgan定律验证: " + (result1 == result2));
System.out.println("De Morgan定律验证: " + (result3 == result4));
}

位运算符

位运算符直接操作数字的二进制位,常用于系统编程、加密算法和性能优化。

graph TB
    A[位运算符] --> B[逻辑位运算]
    A --> C[移位运算]
    
    B --> D[& 按位与]
    B --> E[| 按位或]
    B --> F[^ 按位异或]
    B --> G[~ 按位取反]
    
    C --> H[<< 左移]
    C --> I[>> 算术右移]
    C --> J[>>> 逻辑右移]
    
    D --> K[两位都为1时结果为1]
    E --> L[至少一位为1时结果为1]
    F --> M[两位不同时结果为1]
    G --> N[每位取反]

按位逻辑运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class BitwiseOperators {
public void demonstrateBitwiseLogical() {
// 按位与(&):用于屏蔽位
int num1 = 0b1010; // 10
int num2 = 0b1100; // 12
int andResult = num1 & num2; // 0b1000 = 8

// 按位或(|):用于设置位
int orResult = num1 | num2; // 0b1110 = 14

// 按位异或(^):用于翻转位
int xorResult = num1 ^ num2; // 0b0110 = 6

// 按位取反(~):翻转所有位
int notResult = ~num1; // 对于32位int:0b11111111111111111111111111110101

System.out.println("按位与: " + toBinaryString(num1) + " & " +
toBinaryString(num2) + " = " + toBinaryString(andResult));
System.out.println("按位或: " + toBinaryString(num1) + " | " +
toBinaryString(num2) + " = " + toBinaryString(orResult));
System.out.println("按位异或: " + toBinaryString(num1) + " ^ " +
toBinaryString(num2) + " = " + toBinaryString(xorResult));

// 实际应用:权限管理
final int READ = 0b001; // 1
final int WRITE = 0b010; // 2
final int EXECUTE = 0b100; // 4

int permissions = READ | WRITE; // 拥有读写权限
boolean canRead = (permissions & READ) != 0; // true
boolean canWrite = (permissions & WRITE) != 0; // true
boolean canExecute = (permissions & EXECUTE) != 0; // false

System.out.println("权限检查 - 读: " + canRead + ", 写: " + canWrite + ", 执行: " + canExecute);
}

private String toBinaryString(int value) {
return String.format("%8s", Integer.toBinaryString(value & 0xFF)).replace(' ', '0');
}
}

移位运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public void demonstrateShiftOperators() {
// 左移(<<):相当于乘以2的n次方
int value = 5; // 0b101
int leftShift1 = value << 1; // 0b1010 = 10 (5 * 2^1)
int leftShift2 = value << 2; // 0b10100 = 20 (5 * 2^2)

// 算术右移(>>):保持符号位,相当于除以2的n次方
int positive = 20; // 0b10100
int rightShift1 = positive >> 1; // 0b1010 = 10 (20 / 2^1)
int rightShift2 = positive >> 2; // 0b101 = 5 (20 / 2^2)

// 负数的算术右移
int negative = -20;
int negRightShift = negative >> 1; // -10,符号位保持

// 逻辑右移(>>>):不保持符号位,高位补0
int logicalShift = negative >>> 1; // 大正数,因为符号位被当作普通位

System.out.println("左移演示:");
System.out.println(value + " << 1 = " + leftShift1);
System.out.println(value + " << 2 = " + leftShift2);

System.out.println("右移演示:");
System.out.println(positive + " >> 1 = " + rightShift1);
System.out.println(negative + " >> 1 = " + negRightShift);
System.out.println(negative + " >>> 1 = " + logicalShift);

// 实际应用:快速计算
int fastMultiply = value << 3; // 等价于 value * 8
int fastDivide = value >> 1; // 等价于 value / 2

System.out.println("快速计算: " + value + " * 8 = " + fastMultiply);
System.out.println("快速计算: " + value + " / 2 = " + fastDivide);
}

三元运算符

三元运算符(?:)是Java中唯一的三目运算符,提供了简洁的条件表达式语法。

graph LR
    A[三元运算符] --> B[条件表达式]
    B --> C[condition ? value1 : value2]
    
    C --> D[condition为true
返回value1] C --> E[condition为false
返回value2]

基本用法和应用场景

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class TernaryOperator {
public void demonstrateTernaryOperator() {
// 基本语法:条件 ? 值1 : 值2
int a = 10, b = 20;
int max = (a > b) ? a : b; // 20

// 替代简单的if-else
String message = (a > 0) ? "正数" : "非正数";

// 嵌套三元运算符(不推荐过度使用)
int score = 85;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";

// 空值处理
String input = null;
String result = (input != null) ? input.trim() : "";

// 在方法调用中使用
System.out.println("最大值: " + max);
System.out.println("成绩等级: " + grade);

// 数组初始化中的应用
int[] array = new int[(a > b) ? a : b];

// 返回语句中的使用
boolean isValid = checkValue(a);
String status = isValid ? "有效" : "无效";

System.out.println("状态: " + status);
}

private boolean checkValue(int value) {
return value > 0 && value < 100;
}

// 在方法中直接返回三元表达式的结果
public String getAgeCategory(int age) {
return (age < 18) ? "未成年" :
(age < 60) ? "成年" : "老年";
}

// 在赋值中的复杂应用
public void complexTernaryUsage() {
Integer value1 = 10;
Integer value2 = null;

// 空值安全的比较
int result = (value1 != null && value2 != null) ?
Integer.compare(value1, value2) :
(value1 != null ? 1 : -1);

// 与逻辑运算符结合
boolean condition1 = true;
boolean condition2 = false;
String outcome = (condition1 && condition2) ? "两者都为真" :
(condition1 || condition2) ? "至少一个为真" : "都为假";

System.out.println("复杂条件结果: " + outcome);
}
}

运算符优先级

理解运算符优先级对于编写正确的表达式至关重要。

graph TD
    A[运算符优先级
从高到低] --> B[1. 后缀: [] () ++ --] B --> C[2. 前缀: ++ -- + - ! ~] C --> D[3. 乘除模: * / %] D --> E[4. 加减: + -] E --> F[5. 移位: << >> >>>] F --> G[6. 关系: < <= > >= instanceof] G --> H[7. 相等: == !=] H --> I[8. 按位与: &] I --> J[9. 按位异或: ^] J --> K[10. 按位或: |] K --> L[11. 逻辑与: &&] L --> M[12. 逻辑或: ||] M --> N[13. 三元: ?:] N --> O[14. 赋值: = += -= *= /= %= &= ^= |= <<= >>= >>>=]

优先级示例和最佳实践

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class OperatorPrecedence {
public void demonstratePrecedence() {
// 算术运算符优先级
int result1 = 2 + 3 * 4; // 14,而不是20(先乘除后加减)
int result2 = (2 + 3) * 4; // 20,使用括号改变优先级

// 逻辑运算符优先级
boolean a = true, b = false, c = true;
boolean result3 = a || b && c; // true(&& 优先级高于 ||)
boolean result4 = (a || b) && c; // true,使用括号明确意图

// 位运算与逻辑运算混合
int x = 5, y = 3;
boolean result5 = x > y & x < 10; // true,但容易误解
boolean result6 = (x > y) && (x < 10); // 推荐写法,清晰明确

// 赋值运算符的右结合性
int a1, b1, c1;
a1 = b1 = c1 = 10; // 从右到左执行

// 复杂表达式的分解
int complex = ++x * y-- + (x > y ? x : y);
// 推荐分解为多个简单表达式
++x;
int temp = y--;
int max = (x > y) ? x : y;
int simpleResult = x * temp + max;

System.out.println("算术优先级: " + result1 + " vs " + result2);
System.out.println("逻辑优先级: " + result3 + " vs " + result4);
System.out.println("复杂表达式: " + complex + " vs " + simpleResult);

// 最佳实践:使用括号明确优先级
demonstrateBestPractices();
}

private void demonstrateBestPractices() {
int a = 10, b = 5, c = 2;

// 不推荐:依赖默认优先级
int unclear = a + b * c > a * b + c ? a : b;

// 推荐:使用括号明确意图
int clear = ((a + (b * c)) > ((a * b) + c)) ? a : b;

// 更推荐:分解复杂表达式
int left = a + (b * c);
int right = (a * b) + c;
int result = (left > right) ? a : b;

System.out.println("表达式结果: " + unclear + " = " + clear + " = " + result);
}
}

实际应用案例

综合运算符应用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
public class OperatorApplications {

// 案例1:用户权限系统
public class PermissionSystem {
private static final int READ = 1; // 0001
private static final int WRITE = 2; // 0010
private static final int EXECUTE = 4; // 0100
private static final int DELETE = 8; // 1000

private int userPermissions;

public PermissionSystem(int permissions) {
this.userPermissions = permissions;
}

public void grantPermission(int permission) {
userPermissions |= permission; // 使用按位或添加权限
}

public void revokePermission(int permission) {
userPermissions &= ~permission; // 使用按位与和取反移除权限
}

public boolean hasPermission(int permission) {
return (userPermissions & permission) != 0;
}

public boolean hasAllPermissions(int... permissions) {
int required = 0;
for (int permission : permissions) {
required |= permission;
}
return (userPermissions & required) == required;
}
}

// 案例2:数学计算优化
public class MathUtils {

// 使用位运算进行快速计算
public static boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}

public static int multiplyByPowerOfTwo(int value, int power) {
return value << power; // 等价于 value * (2^power)
}

public static int divideByPowerOfTwo(int value, int power) {
return value >> power; // 等价于 value / (2^power)
}

// 三元运算符优化条件返回
public static int max(int a, int b) {
return (a > b) ? a : b;
}

public static int min(int a, int b) {
return (a < b) ? a : b;
}

// 复合赋值运算符的应用
public static void updateStatistics(int[] stats, int newValue) {
stats[0] += newValue; // 累计和
stats[1] = max(stats[1], newValue); // 最大值
stats[2] = min(stats[2], newValue); // 最小值
stats[3]++; // 计数
}
}

// 案例3:状态机实现
public class StateMachine {
private static final int STATE_INIT = 0;
private static final int STATE_RUNNING = 1;
private static final int STATE_PAUSED = 2;
private static final int STATE_STOPPED = 3;

private int currentState = STATE_INIT;

public boolean canTransition(int fromState, int toState) {
// 使用位运算定义状态转换规则
int validTransitions = getValidTransitions(fromState);
return (validTransitions & (1 << toState)) != 0;
}

private int getValidTransitions(int state) {
switch (state) {
case STATE_INIT:
return (1 << STATE_RUNNING); // 只能转到运行状态
case STATE_RUNNING:
return (1 << STATE_PAUSED) | (1 << STATE_STOPPED); // 可以暂停或停止
case STATE_PAUSED:
return (1 << STATE_RUNNING) | (1 << STATE_STOPPED); // 可以继续或停止
case STATE_STOPPED:
return (1 << STATE_INIT); // 只能重新初始化
default:
return 0;
}
}

public void setState(int newState) {
if (canTransition(currentState, newState)) {
currentState = newState;
System.out.println("状态转换成功: " + getStateName(newState));
} else {
System.out.println("无效的状态转换");
}
}

private String getStateName(int state) {
return (state == STATE_INIT) ? "初始化" :
(state == STATE_RUNNING) ? "运行中" :
(state == STATE_PAUSED) ? "已暂停" :
(state == STATE_STOPPED) ? "已停止" : "未知";
}
}
}

总结

Java运算符是编程的基础工具,掌握它们的正确使用对于编写高效、可读的代码至关重要。通过本文的学习,我们深入了解了:

  1. 算术运算符:包括基本的数学运算和自增自减操作,注意溢出和精度问题
  2. 赋值运算符:简单赋值和复合赋值,简化代码编写
  3. 比较运算符:数值和对象的比较,注意引用与内容的区别
  4. 逻辑运算符:布尔逻辑操作和短路求值机制
  5. 位运算符:底层位操作,用于性能优化和特殊算法
  6. 三元运算符:简洁的条件表达式,提高代码可读性
  7. 运算符优先级:避免歧义,正确构建表达式

在实际编程中,合理使用运算符不仅能提高代码效率,还能增强代码的表达力。建议开发者:

  • 理解每种运算符的特性和限制
  • 注意类型转换和精度问题
  • 合理使用括号明确运算优先级
  • 在复杂表达式中优先考虑代码可读性
  • 熟练运用运算符的特殊用法和优化技巧

掌握这些运算符的精髓,将为后续学习Java的高级特性和编写高质量代码奠定坚实基础。

参考资料