**Java运算符深度剖析:算术关系逻辑与位运算详解**
运算符是Java语言中用于执行各种操作的符号,它们构成了程序逻辑的基础。从简单的算术计算到复杂的位运算,Java提供了丰富的运算符来满足不同的编程需求。
### 算术运算符
算术运算符用于执行基本的数学运算,包括加、减、乘、除、取模等。
```java
public class ArithmeticOperators {
public static void basicArithmetic() {
int a = 15;
int b = 4;
System.out.println("=== 基本算术运算 ===");
System.out.println("a = " + a + ", b = " + b);
System.out.println("加法: a + b = " + (a + b));
System.out.println("减法: a - b = " + (a - b));
System.out.println("乘法: a * b = " + (a * b));
System.out.println("除法: a / b = " + (a / b));
System.out.println("取模: a % b = " + (a % b));
// 整数除法的特点
System.out.println("\n整数除法示例:");
System.out.println("10 / 3 = " + (10 / 3)); // 结果为3,小数部分被截断
// 浮点数除法
double x = 10.0;
double y = 3.0;
System.out.println("浮点数除法: 10.0 / 3.0 = " + (x / y));
}
public static void incrementDecrement() {
System.out.println("\n=== 自增自减运算 ===");
int i = 5;
System.out.println<"BP.1853.HK">("初始值 i = " + i);
// 前缀形式:先运算后使用
System.out.println("++i = " + (++i)); // 输出6
System.out.println("当前 i = " + i); // 输出6
// 后缀形式:先使用后运算
System.out.println("i++ = " + (i++)); // 输出6
System.out.println("当前 i = " + i); // 输出7
System.out.println("--i = " + (--i)); // 输出6
System.out.println("i-- = " + (i--)); // 输出6
System.out.println("最终 i = " + i); // 输出5
}
public static void compoundAssignment() {
System.out.println("\n=== 复合赋值运算 ===");
int num = 10;
System.out.println("初始值: num = " + num);
num += 5; // 等价于 num = num + 5
System.out.println("num += 5 → " + num);
num -= 3; // 等价于 num = num - 3
System.out.println("num -= 3 → " + num);
num *= 2; // 等价于 num = num * 2
System.out.println("num *= 2 → " + num);
num /= 4; // 等价于 num = num / 4
System.out.println("num /= 4 → " + num);
num %= 3; // 等价于 num = num % 3
System.out.println("num %= 3 → " + num);
}
public static void main(String[] args) {
basicArithmetic();
incrementDecrement();
compoundAssignment();
}
}
```
### 关系运算符
关系运算符用于比较两个值之间的关系,返回布尔结果。
```java
public class RelationalOperators {
public static void comparisonOperators() {
int a = 10;
int b = 20;
int c = 10;
System.out.println("=== 关系运算 ===");
System.out.println("a = " + a + ", b = " + b + ", c = " + c);
System.out.println("a == b: " + (a == b)); // 等于
System.out.println("a != b: " + (a != b)); // 不等于
System.out.println("a > b: " + (a > b)); // 大于
System.out.println("a < b: " + (a < b)); // 小于
System.out.println("a >= c: " + (a >= c)); // 大于等于
System.out.println("a <= c: " + (a <= c)); // 小于等于
// 字符串比较的特殊性
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println("\n字符串比较:");
System.out.println("str1 == str2: " + (str1 == str2)); // true,字符串常量池
System.out.println("str1 == str3: " + (str1 == str3)); // false,不同对象
System.out.println("str1.equals(str3): " + str1.equals(str3)); // true,内容相同
}
public static void practicalExamples() {
System.out.println("\n=== 关系运算实际应用 ===");
// 年龄验证
int age = 18;
boolean isAdult = age >= 18;
System.out.println("年龄 " + age + " 是否成年: " + isAdult);
// 成绩等级判断
int score = 85;
boolean isExcellent = score >= 90;
boolean isGood = score >= 80 && score < 90;
boolean isPass = score >= 60;
System.out.println("成绩 " + score + " 分析:");
System.out.println("优秀: " + isExcellent);
System.out.println("良好: " + isGood);
System.out.println("及格: " + isPass);
// 范围检查
int value = 75;
boolean inRange = value >= 0 && value <= 100;
System.out.println("值 " + value + " 是否在0-100范围内: " + inRange);
}
public static void main(String[] args) {
comparisonOperators<"7D.6370.HK">();
practicalExamples();
}
}
```
### 逻辑运算符
逻辑运算符用于组合多个布尔表达式,实现复杂的逻辑判断。
```java
public class LogicalOperators {
public static void basicLogicalOperators() {
System.out.println("=== 基本逻辑运算 ===");
boolean a = true;
boolean b = false;
System.out.println("a = " + a + ", b = " + b);
System.out.println("逻辑与: a && b = " + (a && b));
System.out.println("逻辑或: a || b = " + (a || b));
System.out.println("逻辑非: !a = " + (!a));
System.out.println("逻辑非: !b = " + (!b));
// 短路求值演示
System.out.println("\n=== 短路求值演示 ===");
int x = 10;
int y = 20;
// 由于第一个条件为false,第二个条件不会执行
if (x > 15 && y++ > 10) {
System.out.println("条件成立");
}
System.out.println("y = " + y); // y仍然是20
// 重置y值
y = 20;
// 由于第一个条件为true,第二个条件不会执行
if (x < 15 || y++ > 10) {
System.out.println("条件成立");
}
System.out.println("y = " + y); // y仍然是20
}
public static void complexLogicalExpressions() {
System.out.println("\n=== 复杂逻辑表达式 ===");
int age = 25;
boolean hasLicense = true;
boolean hasInsurance = true;
int accidentCount = 0;
// 驾驶资格检查
boolean canDrive = age >= 18 && hasLicense;
System.out.println("可以驾驶: " + canDrive);
// 保险优惠资格
boolean discountEligible = age >= 25 && hasInsurance && accidentCount == 0;
System.out.println("保险优惠资格: " + discountEligible);
// 租车资格
boolean canRentCar = (age >= 21 && hasLicense) ||
(age >= 25 && hasLicense && hasInsurance);
System.out.println("租车资格: " + canRentCar);
}
public static void inputValidation() {
System.out.println("\n=== 输入验证示例 ===");
String username = "user123";
String password = "pass123";
int loginAttempts = 2;
// 用户名验证
boolean validUsername = username != null &&
username.length() >= 5 &&
username.length() <= 20;
// 密码验证
boolean validPassword = password != null &&
password.length() >= 6;
// 登录尝试限制
boolean withinAttemptLimit = loginAttempts < 3;
// 综合验证
boolean canLogin = validUsername && validPassword && withinAttemptLimit;
System.out.println("用户名有效: " + validUsername);
System.out.println("密码有效: " + validPassword);
System.out.println("在尝试限制内: " + withinAttemptLimit);
System.out.println("可以登录: " + canLogin);
}
public static void main(String[] args) {
basicLogicalOperators();
complexLogicalExpressions();
inputValidation();
}
}
```
### 位运算符
位运算符直接操作整数的二进制位,用于底层编程和性能优化。
```java
public class BitwiseOperators {
public static void basicBitwiseOperations() {
System.out.println("=== 基本位运算 ===");
int a = 5; // 二进制: 0101
int b = 3; // 二进制: 0011
System.out.println("a = " + a + " (二进制: " + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (二进制: " + Integer.toBinaryString(b) + ")");
System.out.println("按位与: a & b = " + (a & b) +
" (二进制: " + Integer.toBinaryString(a & b) + ")");
System.out.println("按位或: a | b = " + (a | b) +
" (二进制: " + Integer.toBinaryString(a | b) + ")");
System.out.println("按位异或: a ^ b = " + (a ^ b) +
" (二进制: " + Integer.toBinaryString(a ^ b) + ")");
System.out.println("按位取反: ~a = " + (~a) +
" (二进制: " + Integer.toBinaryString(~a) + ")");
}
public static void shiftOperations() {
System.out.println("\n=== 移位运算 ===");
int num = 10; // 二进制: 1010
System.out.println("原始值: " + num + " (二进制: " +
String.format<"TN.5283.HK">("%8s", Integer.toBinaryString(num)).replace(' ', '0') + ")");
// 左移
int leftShift = num << 2; // 相当于乘以4
System.out.println("左移2位: " + leftShift + " (二进制: " +
String.format("%8s", Integer.toBinaryString(leftShift)).replace(' ', '0') + ")");
// 右移(带符号)
int rightShift = num >> 1; // 相当于除以2
System.out.println("右移1位: " + rightShift + " (二进制: " +
String.format("%8s", Integer.toBinaryString(rightShift)).replace(' ', '0') + ")");
// 无符号右移
int unsignedRightShift = num >>> 1;
System.out.println("无符号右移1位: " + unsignedRightShift + " (二进制: " +
String.format("%8s", Integer.toBinaryString(unsignedRightShift)).replace(' ', '0') + ")");
// 负数移位示例
int negative = -10;
System.out.println("\n负数示例: " + negative + " (二进制: " +
Integer.toBinaryString(negative) + ")");
System.out.println("负数右移: " + (negative >> 1) + " (二进制: " +
Integer.toBinaryString(negative >> 1) + ")");
System.out.println("负数无符号右移: " + (negative >>> 1) + " (二进制: " +
Integer.toBinaryString(negative >>> 1) + ")");
}
public static void practicalBitwiseApplications() {
System.out.println("\n=== 位运算实际应用 ===");
// 权限管理系统
int READ = 1; // 0001
int WRITE = 2; // 0010
int EXECUTE = 4; // 0100
int DELETE = 8; // 1000
int userPermissions = READ | WRITE; // 0011 - 有读和写权限
System.out.println("用户权限: " + Integer.toBinaryString(userPermissions));
System.out.println("有读权限: " + ((userPermissions & READ) != 0));
System.out.println("有执行权限: " + ((userPermissions & EXECUTE) != 0));
// 添加执行权限
userPermissions |= EXECUTE;
System.out.println("添加执行权限后: " + Integer.toBinaryString(userPermissions));
// 移除写权限
userPermissions &= ~WRITE;
System.out.println("移除写权限后: " + Integer.toBinaryString(userPermissions));
// 奇偶判断
int number = 15;
boolean isEven = (number & 1) == 0;
System.out.println("\n数字 " + number + " 是偶数: " + isEven);
// 快速乘除2
int value = 20;
System.out.println(value + " * 2 = " + (value << 1));
System.out.println(value + " / 2 = " + (value >> 1));
}
public static void main(String[] args) {
basicBitwiseOperations();
shiftOperations();
practicalBitwiseApplications();
}
}
```
### 条件运算符
条件运算符(三元运算符)提供简洁的条件判断语法。
```java
public class ConditionalOperator {
public static void basicConditional() {
System.out.println("=== 条件运算符基础 ===");
int a = 10;
int b = 20;
// 基本用法
int max = (a > b) ? a : b;
System.out.println<"AZ.9134.HK">("a和b中的最大值: " + max);
// 奇偶判断
int number = 15;
String parity = (number % 2 == 0) ? "偶数" : "奇数";
System.out.println(number + " 是 " + parity);
// 成绩等级
int score = 85;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
System.out.println("成绩 " + score + " 的等级: " + grade);
}
public static void practicalApplications() {
System.out.println("\n=== 条件运算符实际应用 ===");
// 用户状态显示
boolean isOnline = true;
String status = isOnline ? "在线" : "离线";
System.out.println("用户状态: " + status);
// 价格计算(含折扣)
double price = 100.0;
boolean isMember = true;
double finalPrice = isMember ? price * 0.9 : price;
System.out.println("最终价格: " + finalPrice);
// 数组边界检查
int[] numbers = {1, 2, 3, 4, 5};
int index = 3;
int value = (index >= 0 && index < numbers.length) ? numbers[index] : -1;
System.out.println("索引 " + index + " 的值: " + value);
}
public static void nestedConditional() {
System.out.println("\n=== 嵌套条件运算符 ===");
int age = 22;
boolean hasLicense = true;
boolean hasCar = false;
String transportation = (age >= 18) ?
(hasLicense ?
(hasCar ? "可以开车" : "可以租车") :
"需要考驾照") :
"年龄不足";
System.out.println("交通方式: " + transportation);
}
public static void main(String[] args) {
basicConditional();
practicalApplications();
nestedConditional();
}
}
```
### 运算符优先级
理解运算符优先级对于编写正确的表达式至关重要。
```java
public class OperatorPrecedence {
public static void precedenceExamples() {
System.out.println("=== 运算符优先级示例 ===");
int a = 5, b = 3, c = 2;
// 不同的优先级会导致不同的结果
int result1 = a + b * c; // 5 + (3 * 2) = 11
int result2 = (a + b) * c; // (5 + 3) * 2 = 16
System.out.println("a + b * c = " + result1);
System.out.println("(a + b) * c = " + result2);
// 逻辑运算符的优先级
boolean <"3W.2597.HK">x = true, y = false, z = true;
boolean logicalResult1 = x || y && z; // true || (false && true) = true
boolean logicalResult2 = (x || y) && z; // (true || false) && true = true
System.out.println("x || y && z = " + logicalResult1);
System.out.println("(x || y) && z = " + logicalResult2);
}
public static void complexExpression() {
System.out.println("\n=== 复杂表达式解析 ===");
int a = 10, b = 5, c = 2;
// 复杂的混合运算
int result = a + ++b * c - a / c;
// 等价于: a + ( (++b) * c ) - (a / c)
// 步骤: 1. ++b → b=6
// 2. 6 * 2 = 12
// 3. a / c = 5
// 4. 10 + 12 - 5 = 17
System.out.println("a + ++b * c - a / c = " + result);
}
public static void precedenceTable() {
System.out.println("\n=== 运算符优先级表 ===");
System.out.println("1. 后缀运算符: [] . (params) expr++ expr--");
System.out.println("2. 一元运算符: ++expr --expr +expr -expr ~ !");
System.out.println("3. 乘性运算符: * / %");
System.out.println("4. 加性运算符: + -");
System.out.println("5. 移位运算符: << >> >>>");
System.out.println("6. 关系运算符: < > <= >= instanceof");
System.out.println("7. 相等运算符: == !=");
System.out.println("8. 位与: &");
System.out.println("9. 位异或: ^");
System.out.println("10. 位或: |");
System.out.println("11. 逻辑与: &&");
System.out.println("12. 逻辑或: ||");
System.out.println("13. 条件运算符: ? :");
System.out.println("14. 赋值运算符: = += -= *= /= %= &= ^= |= <<= >>= >>>=");
}
public static void main(String[] args) {
precedenceExamples();
complexExpression();
precedenceTable();
}
}
```
### 总结
Java运算符体系提供了从基础算术到复杂位操作的完整解决方案:
1. **算术运算符**处理基本的数学计算
2. **关系运算符**实现值的比较和条件判断
3. **逻辑运算符**组合多个布尔条件
4. **位运算符**进行底层二进制操作
5. **条件运算符**简化if-else逻辑
掌握各种运算符的特性和优先级规则,能够帮助开发者编写出更简洁、高效和可读性强的代码。在实际编程中,应根据具体需求选择合适的运算符,并注意使用括号明确运算顺序,避免因优先级问题导致的逻辑错误。