将 If 语句放在另一个 if 块中称为 Java 中的嵌套 If 语句。Java If Else 语句允许我们根据表达式结果(TRUE、FALSE)打印不同的语句。有时,即使条件为 TRUE,我们也需要进一步检查。在这种情况下,我们可以使用嵌套 IF 语句,但请在使用它们时务必小心。
例如,每个人在 18 岁或以上时都有资格工作;否则,他/她不合格。然而,公司不会录用每个人。因此,我们使用另一个 IF 语句,即 Java 嵌套 If 语句,来验证他的教育技能或任何公司特殊要求。在举例之前,让我们先看一下嵌套 If 的语法。
Java 嵌套 If 语法
此编程语言中的嵌套 If 如下所示
if ( test condition 1) {
//If the test condition 1 is TRUE then, it will check for test condition 2
if ( test condition 2) {
//If the test condition 2 is TRUE, these statements will be executed
Test condition 2 True statements;
}
else {
//If the test condition 2 is FALSE, these lines will be executed
Test condition 2 False statements;
}
else {
//If the test condition 1 is FALSE then these lines will be executed
Test condition 1 False statements;
}
Java 嵌套 If 流程图
下图将展示嵌套 If 语句的流程图。

嵌套 If 语句的执行流程为。
- 如果 Condition1 为 FALSE,则执行 STATEMENT3。
- 如果 Test Condition1 为 TRUE,它将检查 Test Condition2。
- 如果表达式为 TRUE,则执行 STATEMENT1。
- 否则执行 STATEMENT2。
Java 嵌套 If Else 示例
嵌套 If else 程序允许用户输入他们的年龄,我们将它存储在 age 变量中。如果给定的年龄小于 18 岁,我们将打印两个语句。当条件不满足时,我们将检查另一个条件(嵌套);如果满足,则打印一些内容。如果表达式结果不满足,则打印其他内容。
请参阅 Java 编程中的 If Else 和 IF Condition 文章。
package ConditionalStatements;
import java.util.Scanner;
public class NestedIf {
private static Scanner sc;
public static void main(String[] args) {
int age;
sc = new Scanner(System.in);
System.out.println(" Please Enter you Age: ");
age = sc.nextInt();
if (age < 18) {
System.out.println("You are Minor.");
System.out.println("You are Not Eligible to Work");
}
else {
if (age >= 18 && age <= 60 ) {
System.out.println("You are Eligible to Work");
System.out.println("Please fill in your details and apply");
}
else {
System.out.println("You are too old to work as per the Government rules");
System.out.println("Please Collect your pension!");
}
}
System.out.println("\nThis Message is coming from Outside the IF ELSE STATEMENT");
}
}
在此 Java 嵌套 if else 程序中,如果该人的年龄小于 18 岁,则他不符合工作资格。如果该人的年龄大于或等于 18 岁,则第一个表达式失败。它将转到 else 语句。Else 语句中还有一个 if 条件(嵌套 If)。
- 它将检查该人的年龄是否大于或等于 18 岁且小于或等于 60 岁。如果表达式被评估为 TRUE,那么他可以申请工作。
- 如果嵌套 If 条件为 FALSE,则根据政府规定,他/她年纪太大,不适合工作。
- 我们还在 If Else 块外放置了一个 System.out.println 函数,它将根据表达式结果执行。
输出 1:从下面的嵌套 if 语句屏幕截图中,您可以看到我们输入的年龄是 16。这里,第一个 If 条件为 TRUE。因此,第一个 if 块内的语句将执行。

我们输入的年龄是 25,这意味着第一个 IF 表达式为 FALSE。它将进入 else 块。在 else 块中,Javac 将检查 if (age>= 18 && age<=60),这是 TRUE。因此,它将打印此块内的代码。
Please Enter you Age:
25
You are Eligible to Work
Please fill in your details and apply
This Message is coming from Outside the IF ELSE STATEMENT
第三次输出:这次,我们将输入年龄 61 来测试嵌套 If。这意味着第一个 IF 条件为 FALSE。它将进入 else 块。在 else 块中,Javac 编译器将检查 if (age>= 18 && age<=60),这是 FALSE。这就是为什么此 程序 将打印子 else 块内的代码。
Please Enter you Age:
61
You are too old to work as per the Government rules
Please Collect your pension!
This Message is coming from Outside the IF ELSE STATEMENT