Java运算符完全指南:让代码学会“计算”和“判断”

运算符是用来对变量和值进行各种操作的符号。比如我们熟悉的加减乘除(+、-、*、/)就是运算符

运算符分类及代码示例

1. 算术运算符:进行数学计算

Java 复制代码
public class ArithmeticOperators {
    public static void main(String[] args) {
        int a = 15;
        int b = 4;
        
        System.out.println("=== 算术运算符示例 ===");
        System.out.println("a = " + a + ", b = " + b);
        System.out.println("加法 a + b = " + (a + b));      // 19
        System.out.println("减法 a - b = " + (a - b));      // 11
        System.out.println("乘法 a * b = " + (a * b));      // 60
        System.out.println("除法 a / b = " + (a / b));      // 3(整数除法)
        System.out.println("取余 a % b = " + (a % b));      // 3(15÷4=3余3)
        
        // 浮点数除法
        double x = 15.0;
        double y = 4.0;
        System.out.println("浮点除法 x / y = " + (x / y));  // 3.75
        
        // 自增自减
        int count = 5;
        System.out.println("初始count = " + count);
        count++;  // 相当于 count = count + 1
        System.out.println("count++后 = " + count);  // 6
        count--;  // 相当于 count = count - 1
        System.out.println("count--后 = " + count);  // 5
    }
}

运行结果:

Java 复制代码
=== 算术运算符示例 ===
a = 15, b = 4
加法 a + b = 19
减法 a - b = 11
乘法 a * b = 60
除法 a / b = 3
取余 a % b = 3
浮点除法 x / y = 3.75
初始count = 5
count++后 = 6
count--后 = 5

2. 关系运算符:进行比较判断

Java 复制代码
public class RelationalOperators {
    public static void main(String[] args) {
        int score1 = 85;
        int score2 = 90;
        int passingScore = 60;
        
        System.out.println("=== 关系运算符示例 ===");
        System.out.println("score1 = " + score1 + ", score2 = " + score2);
        System.out.println("score1 > score2: " + (score1 > score2));      // false
        System.out.println("score1 < score2: " + (score1 < score2));      // true
        System.out.println("score1 >= passingScore: " + (score1 >= passingScore)); // true
        System.out.println("score2 <= 100: " + (score2 <= 100));          // true
        System.out.println("score1 == 85: " + (score1 == 85));            // true
        System.out.println("score1 != score2: " + (score1 != score2));    // true
        
        // 实际应用:判断成绩是否及格
        int myScore = 75;
        boolean isPass = myScore >= passingScore;
        System.out.println("成绩" + myScore + "分是否及格: " + isPass);
    }
}

运行结果:

Java 复制代码
=== 关系运算符示例 ===
score1 = 85, score2 = 90
score1 > score2: false
score1 < score2: true
score1 >= passingScore: true
score2 <= 100: true
score1 == 85: true
score1 != score2: true
成绩75分是否及格: true

3. 逻辑运算符:组合多个条件

Java 复制代码
public class LogicalOperators {
    public static void main(String[] args) {
        boolean isStudent = true;
        boolean hasIDCard = true;
        int age = 20;
        double balance = 150.0;
        
        System.out.println("=== 逻辑运算符示例 ===");
        
        // &&(与):两个条件都满足
        boolean canBorrowBook = isStudent && hasIDCard;
        System.out.println("可以借书(是学生且有证件): " + canBorrowBook);
        
        // ||(或):至少满足一个条件
        boolean canWatchMovie = (age >= 18) || (age < 18 && balance > 100);
        System.out.println("可以看电影(年满18岁或有钱的未成年人): " + canWatchMovie);
        
        // !(非):取反
        boolean isNotStudent = !isStudent;
        System.out.println("不是学生: " + isNotStudent);
        
        // 复杂条件:学生优惠条件
        boolean studentDiscount = isStudent && (age < 22) && (balance > 50);
        System.out.println("享受学生优惠: " + studentDiscount);
        
        // 实际场景:登录验证
        String username = "admin";
        String password = "123456";
        boolean isValidUser = username.equals("admin") && password.equals("123456");
        System.out.println("用户登录成功: " + isValidUser);
    }
}

运行结果:

Java 复制代码
=== 逻辑运算符示例 ===
可以借书(是学生且有证件): true
可以看电影(年满18岁或有钱的未成年人): true
不是学生: false
享受学生优惠: true
用户登录成功: true

4. 赋值运算符:给变量赋值

Java 复制代码
public class AssignmentOperators {
    public static void main(String[] args) {
        System.out.println("=== 赋值运算符示例 ===");
        
        // 基本赋值
        int total = 100;
        System.out.println("初始total = " + total);
        
        // 复合赋值
        total += 50;  // 相当于 total = total + 50
        System.out.println("total += 50 后: " + total);
        
        total -= 30;  // 相当于 total = total - 30
        System.out.println("total -= 30 后: " + total);
        
        total *= 2;   // 相当于 total = total * 2
        System.out.println("total *= 2 后: " + total);
        
        total /= 4;   // 相当于 total = total / 4
        System.out.println("total /= 4 后: " + total);
        
        total %= 3;   // 相当于 total = total % 3
        System.out.println("total %= 3 后: " + total);
        
        // 字符串拼接
        String message = "Hello";
        message += " World";  // 相当于 message = message + " World"
        message += "!";
        System.out.println("拼接后的消息: " + message);
    }
}

运行结果:

Java 复制代码
=== 赋值运算符示例 ===
初始total = 100
total += 50 后: 150
total -= 30 后: 120
total *= 2 后: 240
total /= 4 后: 60
total %= 3 后: 0
拼接后的消息: Hello World!

5. 条件运算符(三元运算符):简洁的条件判断

Java 复制代码
public class ConditionalOperator {
    public static void main(String[] args) {
        int score1 = 85;
        int score2 = 92;
        
        System.out.println("=== 条件运算符示例 ===");
        
        // 语法:条件 ? 值1 : 值2
        // 如果条件为true,返回值1;否则返回值2
        
        // 找出较大的分数
        int maxScore = (score1 > score2) ? score1 : score2;
        System.out.println("较大分数: " + maxScore);
        
        // 判断成绩等级
        int testScore = 78;
        String grade = (testScore >= 90) ? "优秀" : 
                      (testScore >= 80) ? "良好" : 
                      (testScore >= 70) ? "中等" : 
                      (testScore >= 60) ? "及格" : "不及格";
        System.out.println("成绩" + testScore + "分的等级: " + grade);
        
        // 判断奇偶数
        int number = 15;
        String parity = (number % 2 == 0) ? "偶数" : "奇数";
        System.out.println(number + "是" + parity);
    }
}

运行结果:

Java 复制代码
=== 条件运算符示例 ===
较大分数: 92
成绩78分的等级: 中等
15是奇数

6. 综合示例:学生成绩评定系统

Java 复制代码
public class StudentGradeSystem {
    public static void main(String[] args) {
        // 学生信息
        String studentName = "张三";
        int mathScore = 85;
        int englishScore = 92;
        int programmingScore = 78;
        boolean hasGoodAttendance = true;
        
        System.out.println("=== 学生成绩评定系统 ===");
        System.out.println("学生姓名: " + studentName);
        System.out.println("数学成绩: " + mathScore);
        System.out.println("英语成绩: " + englishScore);
        System.out.println("编程成绩: " + programmingScore);
        
        // 计算平均分
        double averageScore = (mathScore + englishScore + programmingScore) / 3.0;
        System.out.println("平均成绩: " + String.format("%.2f", averageScore));
        
        // 判断是否所有科目都及格
        boolean allPass = (mathScore >= 60) && (englishScore >= 60) && (programmingScore >= 60);
        System.out.println("所有科目都及格: " + allPass);
        
        // 判断是否有科目优秀(≥90分)
        boolean hasExcellent = (mathScore >= 90) || (englishScore >= 90) || (programmingScore >= 90);
        System.out.println("有优秀科目: " + hasExcellent);
        
        // 综合评定
        boolean goodStudent = (averageScore >= 80) && hasGoodAttendance && allPass;
        System.out.println("优秀学生评定: " + goodStudent);
        
        // 使用三元运算符给出建议
        String advice = (averageScore >= 85) ? "继续保持优秀表现!" :
                       (averageScore >= 70) ? "表现良好,继续努力!" :
                       "需要加倍努力,加油!";
        System.out.println("学习建议: " + advice);
    }
}

运行结果:

Java 复制代码
=== 学生成绩评定系统 ===
学生姓名: 张三
数学成绩: 85
英语成绩: 92
编程成绩: 78
平均成绩: 85.00
所有科目都及格: true
有优秀科目: true
优秀学生评定: true
学习建议: 继续保持优秀表现!

注意事项

  1. 运算符优先级:乘除优先于加减,逻辑非>算术>关系>逻辑与>逻辑或>赋值
  2. 整数除法陷阱5 / 2 结果是2而不是2.5,要得到小数需用5.0 / 2
  3. 短路求值&&||会出现短路现象,第一个条件能确定结果时不再计算第二个条件
  4. 比较浮点数 :不要直接用==比较浮点数,因为精度问题可能导致错误
  5. =和==区别=是赋值,==是比较,初学者容易混淆
  6. 复合赋值a += b 等价于 a = a + b,但更简洁高效
相关推荐
Lumos_77710 小时前
Linux -- 线程
java·jvm·算法
知兀10 小时前
【MybatisPlus】后端用枚举类,数据库用tinyint,存在枚举类型转换
java
StockTV10 小时前
印度股票实时数据 NSE和BSE的实时行情、K 线及指数数据
java·开发语言·spring boot·python
User_芊芊君子10 小时前
【OpenAI 把 AI 玩明白了】:自主推理 + 动态知识图谱,这 4 个技术突破要颠覆行业
java·人工智能·知识图谱
c++之路11 小时前
C++20概述
java·开发语言·c++20
Championship.23.2411 小时前
Linux Top 命令族深度解析与实战指南
java·linux·服务器·top·linux调试
橘子海全栈攻城狮11 小时前
【最新源码】养老院系统管理A013
java·spring boot·后端·web安全·微信小程序
逻辑驱动的ken11 小时前
Java高频面试考点18
java·开发语言·数据库·算法·面试·职场和发展·哈希算法
冷雨夜中漫步12 小时前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
直奔標竿12 小时前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring