Java条件语句 - if-else #

一、条件语句概述 #

条件语句根据条件表达式的真假,决定执行哪个代码分支。

二、if语句 #

2.1 基本语法 #

java
if (条件表达式) {
    // 条件为true时执行
}

2.2 使用示例 #

java
int age = 20;

if (age >= 18) {
    System.out.println("成年人");
}

// 简单语句可以省略大括号(不推荐)
if (age >= 18)
    System.out.println("成年人");

2.3 代码块 #

java
int score = 85;

if (score >= 60) {
    String result = "及格";
    System.out.println(result);
}
// result 变量在代码块外不可访问

三、if-else语句 #

3.1 基本语法 #

java
if (条件表达式) {
    // 条件为true时执行
} else {
    // 条件为false时执行
}

3.2 使用示例 #

java
int age = 15;

if (age >= 18) {
    System.out.println("成年人");
} else {
    System.out.println("未成年人");
}

3.3 三元运算符替代 #

java
int age = 15;

// if-else
String status;
if (age >= 18) {
    status = "成年人";
} else {
    status = "未成年人";
}

// 三元运算符(更简洁)
String status2 = age >= 18 ? "成年人" : "未成年人";

四、if-else if-else语句 #

4.1 基本语法 #

java
if (条件1) {
    // 条件1为true执行
} else if (条件2) {
    // 条件1为false,条件2为true执行
} else if (条件3) {
    // 条件1、2为false,条件3为true执行
} else {
    // 所有条件都为false执行
}

4.2 使用示例 #

java
int score = 85;
String grade;

if (score >= 90) {
    grade = "优秀";
} else if (score >= 80) {
    grade = "良好";
} else if (score >= 70) {
    grade = "中等";
} else if (score >= 60) {
    grade = "及格";
} else {
    grade = "不及格";
}

System.out.println("成绩等级: " + grade);

4.3 执行流程 #

java
int num = 75;

if (num > 90) {
    System.out.println("大于90");
} else if (num > 80) {
    System.out.println("大于80");
} else if (num > 70) {
    System.out.println("大于70");  // 执行这里,然后跳出
} else if (num > 60) {
    System.out.println("大于60");  // 不会执行
}

五、嵌套if语句 #

5.1 基本用法 #

java
int age = 25;
boolean hasLicense = true;

if (age >= 18) {
    if (hasLicense) {
        System.out.println("可以驾驶");
    } else {
        System.out.println("需要考取驾照");
    }
} else {
    System.out.println("年龄不够");
}

5.2 使用逻辑运算符简化 #

java
int age = 25;
boolean hasLicense = true;

// 嵌套if
if (age >= 18) {
    if (hasLicense) {
        System.out.println("可以驾驶");
    }
}

// 使用逻辑运算符(更简洁)
if (age >= 18 && hasLicense) {
    System.out.println("可以驾驶");
}

六、条件表达式 #

6.1 比较表达式 #

java
int a = 10, b = 20;

if (a > b) {
    System.out.println("a大于b");
}

if (a == b) {
    System.out.println("a等于b");
}

if (a != b) {
    System.out.println("a不等于b");
}

6.2 逻辑表达式 #

java
int age = 25;
boolean hasId = true;

// 与运算
if (age >= 18 && hasId) {
    System.out.println("可以进入");
}

// 或运算
if (age < 12 || age > 65) {
    System.out.println("票价优惠");
}

// 非运算
if (!hasId) {
    System.out.println("请出示证件");
}

6.3 方法调用作为条件 #

java
String input = "Hello";

if (input.isEmpty()) {
    System.out.println("输入为空");
}

if (input.startsWith("H")) {
    System.out.println("以H开头");
}

// 注意空指针
String s = null;
if (s != null && s.length() > 0) {  // 安全
    System.out.println(s);
}

七、常见模式 #

7.1 范围判断 #

java
int score = 85;

// 判断是否在范围内
if (score >= 0 && score <= 100) {
    System.out.println("有效分数");
}

// 判断是否在范围外
if (score < 0 || score > 100) {
    System.out.println("无效分数");
}

7.2 多条件判断 #

java
String role = "admin";

if ("admin".equals(role)) {
    System.out.println("管理员权限");
} else if ("user".equals(role)) {
    System.out.println("普通用户权限");
} else if ("guest".equals(role)) {
    System.out.println("访客权限");
} else {
    System.out.println("未知角色");
}

7.3 输入验证 #

java
public static boolean isValidAge(String input) {
    if (input == null || input.isEmpty()) {
        return false;
    }
    
    try {
        int age = Integer.parseInt(input);
        return age >= 0 && age <= 150;
    } catch (NumberFormatException e) {
        return false;
    }
}

7.4 早返回模式 #

java
public String process(String input) {
    // 早返回:先处理异常情况
    if (input == null) {
        return "输入为空";
    }
    if (input.isEmpty()) {
        return "输入为空字符串";
    }
    
    // 处理正常逻辑
    return "处理结果: " + input.toUpperCase();
}

八、注意事项 #

8.1 大括号的使用 #

java
// 推荐:始终使用大括号
if (condition) {
    doSomething();
}

// 不推荐:省略大括号
if (condition)
    doSomething();
    doAnother();  // 这行不在if块中!

8.2 空指针检查 #

java
String s = null;

// 错误:可能空指针
// if (s.equals("Hello")) { }

// 正确:先检查null
if (s != null && s.equals("Hello")) { }

// 更好:常量在前
if ("Hello".equals(s)) { }

8.3 赋值与比较 #

java
int a = 10;

// 错误:= 是赋值
// if (a = 10) { }  // 编译错误

// 正确:== 是比较
if (a == 10) { }

8.4 浮点数比较 #

java
double a = 0.1 + 0.2;

// 错误:浮点精度问题
if (a == 0.3) { }  // false

// 正确:使用误差范围
if (Math.abs(a - 0.3) < 1e-10) { }

九、最佳实践 #

9.1 保持条件简单 #

java
// 不推荐:复杂条件
if ((user != null && user.isActive()) && 
    (user.getAge() >= 18 && user.hasPermission("read"))) {
    // ...
}

// 推荐:提取变量
boolean isUserValid = user != null && user.isActive();
boolean canRead = isUserValid && user.getAge() >= 18 && user.hasPermission("read");

if (canRead) {
    // ...
}

9.2 避免深层嵌套 #

java
// 不推荐:深层嵌套
if (condition1) {
    if (condition2) {
        if (condition3) {
            doSomething();
        }
    }
}

// 推荐:早返回
if (!condition1) return;
if (!condition2) return;
if (!condition3) return;
doSomething();

9.3 使用switch替代多重if #

java
// 多个相等判断时,考虑使用switch
int day = 3;
String dayName;

switch (day) {
    case 1: dayName = "周一"; break;
    case 2: dayName = "周二"; break;
    case 3: dayName = "周三"; break;
    default: dayName = "其他";
}

十、总结 #

语句 说明
if 单条件判断
if-else 二选一
if-else if-else 多选一
嵌套if 多层条件判断

条件语句要点:

  • 始终使用大括号
  • 注意空指针检查
  • 保持条件简单
  • 避免深层嵌套
  • 使用早返回模式
最后更新:2026-03-26