Skip to content

Java 判断语句

判断结构允许你的程序根据某些条件是真 (true) 还是假 (false) 来选择不同的执行路径。Java 提供了几种用于此目的的语句:

  • if 语句(包括 if-else 和 if-else if-else)
  • switch 语句(包括传统 switch 和现代 switch 表达式)

最简单的判断语句。只有当指定的布尔表达式求值为 true 时,它才会执行一个代码块。

if (boolean_expression) {
// 如果表达式为真则执行的语句
}
// 这里的代码无论如何都会执行

如果 boolean_expression 为 true,则执行大括号 {} 内的代码。如果为 false,则跳过该代码块,执行从 if 语句的结束大括号之后继续。

public class BasicIfExample {
public static void main(String[] args) {
int score = 75;
if (score >= 60) {
System.out.println("Congratulations, you passed!");
}
System.out.println("Execution continues...");
}
}

输出:

Congratulations, you passed!
Execution continues...

一个 if 语句可以跟随一个可选的 else 块。else 块只在 if 语句的布尔表达式为 false 时执行。

if (boolean_expression) {
// 当布尔表达式为真时执行
} else {
// 当布尔表达式为假时执行
}
public class IfElseExample {
public static void main(String[] args) {
int temperature = 15;
if (temperature > 25) {
System.out.println("It's a hot day!");
} else {
System.out.println("It's not too hot today.");
}
}
}

输出:

It's not too hot today.

用于按顺序检查多个条件。第一个求值为 true 的条件会执行其对应的代码块,其余的 else if 和 else 块将被跳过。最终的 else 块(可选)在之前所有 if 或 else if 条件都为 false 时执行。

要点:

  • 一个 if 可以有零个或多个 else if 块。
  • 一个 if 可以有零个或一个 else 块,它必须位于所有 else if 块之后。
  • 一旦某个 if 或 else if 条件满足,其代码块会执行,并且整个结构会退出。
if (condition_1) {
// 如果 condition_1 为真则执行
} else if (condition_2) {
// 如果 condition_1 为假且 condition_2 为真则执行
} else if (condition_3) {
// 如果条件 1 和 2 为假且 condition_3 为真则执行
} else {
// 如果以上所有条件都不为真则执行(可选)
}
public class GradingExample {
public static void main(String[] args) {
int score = 85;
char grade;
if (score >= 90) {
grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Your grade is: " + grade);
}
}

输出:

Your grade is: B

你可以将一个 if 或 if-else 结构放在另一个 if 或 else 块内部。这允许进行更复杂的条件检查,但过度嵌套会使代码难以阅读。

if (outer_condition) {
// 外层条件为真
if (inner_condition) {
// 外层和内层条件都为真
} else {
// 外层为真,内层为假
}
} else {
// 外层条件为假
}
public class NestedIfExample {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
System.out.println("Eligible to drive based on age.");
if (hasLicense) {
System.out.println("Authorized to drive.");
} else {
System.out.println("Needs a driving license.");
}
} else {
System.out.println("Not eligible to drive yet.");
}
}
}

输出:

Eligible to drive based on age.
Authorized to drive.

switch 语句允许将一个变量与一系列值(case)进行相等性测试。当需要针对单个变量检查多个常量值时,它通常是冗长的 if-else if-else 链的更清晰的替代方案。

switch (expression) {
case value1:
// Statements for value1
break; // 关键:退出 switch
case value2:
// Statements for value2
break;
// ... 其他 case
default: // 可选:如果没有匹配的 case 则执行
// Default 语句
// 如果是最后一个代码块,这里不需要 break
}
  • 表达式必须求值为 byte、short、char、int 及其对应的包装类型(Byte、Short、Character、Integer)、enum 类型(从 Java 5 开始)或 String(从 Java 7 开始)。
  • 每个 case 值必须是与表达式类型兼容的常量(字面量或 final 变量)。
  • 不允许有重复的 case 值。
  • break 语句至关重要。如果省略,执行会“穿透”到下一个 case 的语句,直到遇到 break 或 switch 结束。这是常见的错误来源。
  • default case 是可选的,如果没有任何 case 值与表达式匹配,则执行它。它可以出现在任何位置,但习惯上放在最后。
  • 如果 default 不是最后一个代码块,它需要一个 break 来防止穿透。
public class TraditionalSwitchExample {
public static void main(String[] args) {
int dayOfWeek = 3; // 1=周日, 2=周一, ..., 7=周六
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break; // 即使在最后也是好的做法
}
System.out.println("The day is: " + dayName);
}
}

输出:

The day is: Tuesday
public class SwitchFallThrough {
public static void main(String[] args) {
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B': // 这里没有 break!
case 'C':
System.out.println("Well done");
break;
case 'D':
System.out.println("You passed");
break;
case 'F':
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade");
}
// 输出: Well done (因为执行从 'B' 穿透到了 'C')
}
}

增强型 switch (Switch 表达式, Java 14+)

Section titled “增强型 switch (Switch 表达式, Java 14+)”

Java 14 引入了增强型 switch 特性,既可以作为语句使用,也可以作为表达式(返回一个值)使用。它们提供了更简洁的语法,默认消除了穿透,并提高了代码清晰度。

// 作为语句
switch (expression) {
case value1 -> // 单条语句;
case value2 -> {
// 语句块
}
// ... 其他 case
default -> // Default 语句或块;
}
// 作为表达式(返回一个值)
ResultType result = switch (expression) {
case value1 -> valueToReturn1;
case value2, value3 -> valueToReturn2; // 每个 case 包含多个标签
case value4 -> {
// 代码块中的复杂逻辑
yield calculatedValue; // 使用 yield 从代码块返回值
}
default -> defaultValue;
}; // 注意作为表达式使用时需要分号
  • 箭头语法 (->):箭头右侧的代码仅针对该 case 执行。没有穿透!
  • 多个 case 标签:你可以将多个常量分组到同一个执行块(例如,case 'B', 'C' -> ...)。
  • 无需 break:箭头语法本身就阻止了穿透。
  • 穷举性(对于表达式):当作为表达式使用时,switch 必须覆盖表达式的所有可能值(通过 case 标签或 default 分支)以确保总会返回一个值。编译器会强制执行此规则。
  • yield 关键字:在箭头 (->) 右侧的代码块 ({}) 内使用,用于在 switch 表达式中为该 case 返回一个值。
public class EnhancedSwitchExample {
public static void main(String[] args) {
int dayOfWeek = 3; // 1=周一, ..., 7=周日
String dayType = switch (dayOfWeek) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> {
System.out.println("Invalid day number: " + dayOfWeek);
yield "Unknown"; // 从代码块返回的值
}
};
System.out.println("Day type: " + dayType);
}
}

输出:

Day type: Weekday
  • 对于复杂的布尔条件、范围检查(score > 90)或检查多个不同的变量时,使用 if-else if-else。
  • 当将单个变量与一组离散的常量值(int、String、enum)进行比较时,使用 switch(尤其是增强型 switch)。在这些场景下,它通常更具可读性。

在了解如何进行判断之后,下一章将探讨循环控制语句(while、do-while、for),它们允许你重复执行代码块。