Java 条件语句

if、if...else、if...else if...else 与嵌套条件。

Beginner
Key Points条件必须是 boolean,不能像 C 那样用数字;else 总是就近匹配,多分支用 else if 从上往下命中即停。

if 语句

if (booleanExpr) runs the block when true. The condition must be a boolean: if (1) does not compile, unlike C/C++.

Java
public class IfDemo {
    public static void main(String[] args) {
        int x = 10;

        if (x < 20) {
            System.out.println("This is if statement");
        }
    }
}
Output
This is if statement

if...else 语句

True takes the if branch, false takes else — exactly one runs. Always keep the braces even for one statement; omitting them invites bugs when code is added later.

Java
public class IfElse {
    public static void main(String[] args) {
        int x = 30;

        if (x < 20) {
            System.out.println("This is if statement");
        } else {
            System.out.println("This is else statement");
        }
    }
}
Output
This is else statement

if...else if...else 语句

Multiple branches are tested in order and the first true one wins, so order conditions from specific to general. The final else is a catch-all and may be omitted.

Java
public class IfElseIf {
    public static void main(String[] args) {
        int x = 30;

        if (x == 10) {
            System.out.println("Value of X is 10");
        } else if (x == 20) {
            System.out.println("Value of X is 20");
        } else if (x == 30) {
            System.out.println("Value of X is 30");
        } else {
            System.out.println("This is else statement");
        }
    }
}
Output
Value of X is 30

嵌套 if 语句

An if block may contain another if. An else always binds to the nearest unmatched if, so always brace nested conditions to avoid ambiguity.

Java
public class NestedIf {
    public static void main(String[] args) {
        int x = 30;
        int y = 10;

        if (x == 30) {
            if (y == 10) {
                System.out.println("X = 30 and Y = 10");
            }
        }
    }
}
Output
X = 30 and Y = 10

Friends & Partners