Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

if — conditional selection

if — conditional selection: An if statement selects a branch from a boolean expression; an optional else belongs to the nearest unmatched if unless braces change the structure.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

if

An if statement selects a branch from a boolean expression; an optional else belongs to the nearest unmatched if unless braces change the structure.

Use braces and guard conditions, placing an expensive or unsafe check to the right of a controlling && or ||.

The condition does not accept a number or reference as some languages do; a null Boolean is unboxed and throws NullPointerException.

Without else, false continues after the statement; an else-if chain executes at most one branch, the first whose condition is true.

The first if short-circuits before dereferencing null and prints missing; 72 reaches the first true else-if branch and prints pass.

Examples

public class Main {
    public static void main(String[] args) {
        String text = null;
        if (text != null && !text.isBlank()) {
            System.out.println(text);
        } else {
            System.out.println("missing");
        }
        int score = 72;
        if (score >= 90) System.out.println("excellent");
        else if (score >= 60) System.out.println("pass");
        else System.out.println("retry");
    }
}

Result

missing
pass

The first if short-circuits before dereferencing null and prints missing; 72 reaches the first true else-if branch and prints pass.

Sources