前言 运算符是编程语言中执行特定数学、关系或逻辑运算的符号。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; double x = 3.14 ; double y = 2.86 ; double result = x + y; String str1 = "Hello" ; String str2 = "World" ; String message = str1 + " " + str2; String info = "Result: " + sum; 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; int negative = -difference; double d1 = 1.0 ; double d2 = 0.9 ; double diff = d1 - d2; 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; double radius = 5.0 ; double area = Math.PI * radius * radius; int largeNum1 = Integer.MAX_VALUE; int largeNum2 = 2 ; int overflow = largeNum1 * largeNum2; 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; double preciseResult = (double ) dividend / divisor; try { int result = dividend / 0 ; } catch (ArithmeticException e) { System.out.println("整数除零异常: " + e.getMessage()); } double floatDivision = 1.0 / 0.0 ; double nanResult = 0.0 / 0.0 ; 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; 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; double floatMod = 5.5 % 2.0 ; int negativeMod1 = -17 % 3 ; int negativeMod2 = 17 % -3 ; int negativeMod3 = -17 % -3 ; 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; System.out.println("前缀自增: a=" + a + ", preIncrement=" + preIncrement); int b = 5 ; int postIncrement = b++; System.out.println("后缀自增: b=" + b + ", postIncrement=" + postIncrement); System.out.println("前缀自增循环:" ); for (int i = 0 ; i < 3 ; ++i) { System.out.print(i + " " ); } System.out.println("\n后缀自增循环:" ); for (int i = 0 ; i < 3 ; i++) { System.out.print(i + " " ); } int x = 10 ; int result1 = x++ + ++x; int y = 10 ; int result2 = ++y + y++; 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 ; String str1 = "Original" ; String str2 = str1; 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 -= 3 ; value *= 2 ; value /= 4 ; value %= 5 ; String message = "Hello" ; message += " World" ; message += "!" ; byte b = 10 ; b += 1 ; int flags = 0b1010 ; flags &= 0b1100 ; flags |= 0b0011 ; flags ^= 0b1111 ; 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); boolean notEqual = (a != b); boolean greater = (b > a); boolean less = (a < b); boolean greaterEqual = (a >= c); boolean lessEqual = (a <= b); double d1 = 0.1 + 0.2 ; double d2 = 0.3 ; boolean floatEqual = (d1 == d2); final double EPSILON = 1e-10 ; boolean correctFloatEqual = Math.abs(d1 - d2) < EPSILON; 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" ; boolean referenceEqual1 = (str1 == str2); boolean referenceEqual2 = (str3 == str4); boolean contentEqual = str1.equals(str2); String nullStr = null ; boolean nullComparison = (nullStr == null ); boolean safeComparison = Objects.equals(nullStr, "test" ); int [] array1 = {1 , 2 , 3 }; int [] array2 = {1 , 2 , 3 }; boolean arrayRefEqual = (array1 == array2); boolean arrayContentEqual = Arrays.equals(array1, array2); 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; int x = 5 ; int y = 0 ; if (y != 0 && x / y > 2 ) { 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; 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; boolean original = false ; boolean doubleNot = !!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 )) { System.out.println("已成年" ); } boolean a = true , b = false ; boolean result1 = !(a && b); boolean result2 = (!a) || (!b); boolean result3 = !(a || b); boolean result4 = (!a) && (!b); 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 ; int num2 = 0b1100 ; int andResult = num1 & num2; int orResult = num1 | num2; int xorResult = num1 ^ num2; int notResult = ~num1; 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 ; final int WRITE = 0b010 ; final int EXECUTE = 0b100 ; int permissions = READ | WRITE; boolean canRead = (permissions & READ) != 0 ; boolean canWrite = (permissions & WRITE) != 0 ; boolean canExecute = (permissions & EXECUTE) != 0 ; 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 () { int value = 5 ; int leftShift1 = value << 1 ; int leftShift2 = value << 2 ; int positive = 20 ; int rightShift1 = positive >> 1 ; int rightShift2 = positive >> 2 ; int negative = -20 ; int negRightShift = negative >> 1 ; 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 ; int fastDivide = value >> 1 ; 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 () { int a = 10 , b = 20 ; int max = (a > b) ? a : b; 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 ; int result2 = (2 + 3 ) * 4 ; boolean a = true , b = false , c = true ; boolean result3 = a || b && c; boolean result4 = (a || b) && c; int x = 5 , y = 3 ; boolean result5 = x > y & x < 10 ; 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 { public class PermissionSystem { private static final int READ = 1 ; private static final int WRITE = 2 ; private static final int EXECUTE = 4 ; private static final int DELETE = 8 ; 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; } } 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; } public static int divideByPowerOfTwo (int value, int power) { return value >> 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 ]++; } } 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运算符是编程的基础工具,掌握它们的正确使用对于编写高效、可读的代码至关重要。通过本文的学习,我们深入了解了:
算术运算符 :包括基本的数学运算和自增自减操作,注意溢出和精度问题
赋值运算符 :简单赋值和复合赋值,简化代码编写
比较运算符 :数值和对象的比较,注意引用与内容的区别
逻辑运算符 :布尔逻辑操作和短路求值机制
位运算符 :底层位操作,用于性能优化和特殊算法
三元运算符 :简洁的条件表达式,提高代码可读性
运算符优先级 :避免歧义,正确构建表达式
在实际编程中,合理使用运算符不仅能提高代码效率,还能增强代码的表达力。建议开发者:
理解每种运算符的特性和限制
注意类型转换和精度问题
合理使用括号明确运算优先级
在复杂表达式中优先考虑代码可读性
熟练运用运算符的特殊用法和优化技巧
掌握这些运算符的精髓,将为后续学习Java的高级特性和编写高质量代码奠定坚实基础。
参考资料