EMZETT.
Login

if Statement

In short: The basic conditional branch — a block of code only runs if a boolean condition evaluates to true.

In more detail: The condition in the parentheses must be a boolean in Java — unlike, for example, in C, any non-zero number isn’t enough. With only one statement in the block, the curly braces are optional, but usually still recommended for readability and error-avoidance reasons.

if (age >= 18) {
    System.out.println("Adult");
}

In Depth

int age = 20;
 
// Curly braces optional for exactly one statement - still recommended
if (age >= 18)
    System.out.println("Adult");
 
// Classic beginner mistake: the semicolon right after the condition
if (age >= 18); { // this ; ends the if immediately - the block ALWAYS runs
    System.out.println("Always runs, no matter what age is!");
}
 
// Several conditions combined
if (age >= 18 && age < 65) {
    System.out.println("Working age");
}

The accidental semicolon right after the if condition is one of the most classic, hard-to-find Java beginner mistakes: if (condition); is syntactically valid (an empty statement as the “body” of the if), which makes the actually intended, following block ALWAYS run, regardless of the condition — with no compiler error or warning in older Java versions. Modern IDEs usually flag this pattern as a warning. The mandatory curly braces for blocks with several statements (and the convention of using them even for just one statement) prevents a related class of error: if a second line is later added to the “block” without adding braces, that second line no longer syntactically belongs to the if and always runs.

Nested if statements

if statements can be nested arbitrarily to represent multi-level conditions:

if (isLoggedIn) {
    if (hasPermission) {
        System.out.println("Access granted");
    }
}

Two independent but jointly checked conditions can equivalently also be written with a single &&-combined if (if (isLoggedIn && hasPermission)) — functionally identical, but with more than two or three conditions, a deeply nested structure quickly becomes cluttered (a “pyramid of doom”). So-called “guard clauses” (an early return when a precondition isn’t met) are often the more readable alternative in such cases, because they reduce the overall nesting depth.

Returning boolean expressions directly

A common beginner pattern that can be simplified:

// Cumbersome
boolean isAdult;
if (age >= 18) {
    isAdult = true;
} else {
    isAdult = false;
}
 
// Direct, since the comparison itself already returns a boolean
boolean isAdult2 = age >= 18;

An if that only assigns or returns true/false depending on a condition is practically always unnecessary — the comparison operator itself already delivers the desired boolean value.

See also: if…else, Comparison Operators, Logical Operators