☕ Java

if Statement

The if statement is the most fundamental control flow construct in Java. It evaluates a boolean expression and executes a block of code only if the expression is true. If the condition is false the block is skipped entirely and execution continues with the next statement after the if block.

Syntax and Basic Usage

The if statement requires a boolean expression in parentheses followed by a block of code in curly braces. The block executes only when the condition evaluates to true. The curly braces are technically optional for single-statement bodies, but omitting them is a common source of bugs and should be avoided.
Java
// ── Basic syntax: ────────────────────────────────────────────────────
//
//  if (condition) {
//      // statements executed only when condition is true
//  }
//  // execution always continues here

// ── Simple example: ───────────────────────────────────────────────────
int temperature = 35;

if (temperature > 30) {
    System.out.println("It is hot outside.");   // executes — 35 > 30
}
System.out.println("Check complete.");          // always executes

// ── Condition is false — block skipped: ──────────────────────────────
int temperature2 = 20;

if (temperature2 > 30) {
    System.out.println("It is hot outside.");   // SKIPPED — 20 > 30 is false
}
System.out.println("Check complete.");          // executes

// ── Multiple statements in the block: ────────────────────────────────
int speed = 90;
int speedLimit = 80;

if (speed > speedLimit) {
    int excess = speed - speedLimit;
    System.out.println("Speeding by " + excess + " km/h.");
    System.out.println("Fine issued.");
    System.out.println("Points added to licence.");
}

// ── Single statement without braces (avoid in practice): ─────────────
int age = 20;
if (age >= 18)
    System.out.println("Adult");        // works but risky

// WHY braces matter — classic bug:
if (age >= 18)
    System.out.println("Adult");
    System.out.println("Can vote.");    // NOT part of if — always executes!
//                                        looks like it is inside the if,
//                                        but indentation is just cosmetic.

// CORRECT — always use braces:
if (age >= 18) {
    System.out.println("Adult");
    System.out.println("Can vote.");    // now correctly inside the if
}

Boolean Expressions in if Conditions

The condition inside an if statement must be a boolean expression — any expression that evaluates to true or false. Java does not allow assignments or integer values as conditions (unlike C/C++). Understanding which expressions produce booleans prevents common compile errors and subtle logic bugs.
Java
// ── Comparison operators — produce boolean: ──────────────────────────
int x = 10, y = 20;

if (x == y)  { System.out.println("Equal"); }
if (x != y)  { System.out.println("Not equal"); }       // executes
if (x <  y)  { System.out.println("Less than"); }       // executes
if (x <= y)  { System.out.println("Less or equal"); }   // executes
if (x >  y)  { System.out.println("Greater than"); }
if (x >= y)  { System.out.println("Greater or equal"); }

// ── Logical operators — combine booleans: ─────────────────────────────
int score = 75;
boolean passed = true;

if (score >= 60 && passed) {
    System.out.println("Eligible for certificate"); // both must be true
}

if (score < 50 || !passed) {
    System.out.println("Must retake the course");   // either condition true
}

// ── Boolean variable directly as condition: ───────────────────────────
boolean isLoggedIn = true;

if (isLoggedIn) {                   // same as: if (isLoggedIn == true)
    System.out.println("Welcome back!");
}

if (!isLoggedIn) {                  // same as: if (isLoggedIn == false)
    System.out.println("Please log in.");
}

// ── Method return values as conditions: ───────────────────────────────
String name = "Alice";
List<String> items = new ArrayList<>();

if (name.isEmpty()) {
    System.out.println("Name is empty");
}

if (name.startsWith("A")) {
    System.out.println("Name starts with A");       // executes
}

if (items.isEmpty()) {
    System.out.println("Cart is empty");            // executes
}

// ── Common mistake — assignment instead of comparison: ────────────────
boolean flag = false;
// if (flag = true) { }    // COMPILE ERROR in Java (unlike C++)
// Java prevents accidental assignment in conditions.
if (flag == true) { }      // correct comparison
if (flag) { }              // idiomatic — preferred

Compound Conditions

Real-world conditions often check multiple criteria simultaneously. Java's logical operators && (AND), || (OR), and ! (NOT) combine boolean expressions into compound conditions. Java uses short-circuit evaluation — with &&, if the left side is false the right side is never evaluated; with ||, if the left side is true the right side is never evaluated.
Java
// ── AND (&&) — both conditions must be true: ─────────────────────────
int age   = 25;
boolean hasLicence = true;

if (age >= 18 && hasLicence) {
    System.out.println("Can drive");    // executes
}

// ── OR (||) — at least one condition must be true: ────────────────────
boolean isWeekend = false;
boolean isHoliday = true;

if (isWeekend || isHoliday) {
    System.out.println("Day off!");     // executes — isHoliday is true
}

// ── NOT (!) — inverts the condition: ─────────────────────────────────
boolean isRaining = false;

if (!isRaining) {
    System.out.println("Go for a walk"); // executes — !false = true
}

// ── Short-circuit evaluation — right side not evaluated if unnecessary: ─
String text = null;

// Safe — null check first: if text is null, .length() is never called:
if (text != null && text.length() > 5) {
    System.out.println("Long text");
}

// Unsafe — NullPointerException if text is null:
// if (text.length() > 5 && text != null) { }   // NPE before null check!

// ── Complex compound condition — use parentheses for clarity: ─────────
int salary   = 50000;
int yearsExp = 5;
boolean hasDegree = true;

if ((salary > 40000 && yearsExp >= 3) || hasDegree) {
    System.out.println("Eligible for senior role");
}

// ── Readability tip — extract complex conditions to named variables: ──
boolean sufficientExperience = yearsExp >= 3 && salary > 40000;
boolean qualifiedByEducation = hasDegree;

if (sufficientExperience || qualifiedByEducation) {
    System.out.println("Eligible for senior role");  // same result, clearer
}

Practical Examples

The if statement appears in virtually every Java program. These examples show the most common real-world patterns — input validation, null safety, range checking, and enum-based decisions.
Java
// ── Input validation: ────────────────────────────────────────────────
public void setAge(int age) {
    if (age < 0 || age > 150) {
        throw new IllegalArgumentException(
            "Age must be between 0 and 150, got: " + age);
    }
    this.age = age;
}

// ── Null safety: ──────────────────────────────────────────────────────
public String getDisplayName(User user) {
    if (user == null) {
        return "Guest";
    }
    if (user.getName() == null || user.getName().isBlank()) {
        return "Anonymous";
    }
    return user.getName();
}

// ── Range checking: ───────────────────────────────────────────────────
public String classifyBMI(double bmi) {
    if (bmi < 18.5) {
        return "Underweight";
    }
    if (bmi < 25.0) {
        return "Normal weight";
    }
    if (bmi < 30.0) {
        return "Overweight";
    }
    return "Obese";
    // Note: no else needed — each if returns early.
    // This is the "guard clause" or "early return" pattern.
}

// ── Business rule: ────────────────────────────────────────────────────
public double calculateDiscount(Customer customer, double orderTotal) {
    double discount = 0.0;

    if (customer.isPremium()) {
        discount = 0.15;    // 15% for premium customers
    }

    if (orderTotal > 500.0) {
        discount += 0.05;   // extra 5% for large orders
    }

    if (customer.hasCoupon()) {
        discount += 0.10;   // extra 10% with coupon
    }

    return discount;
}

// ── Checking collection state: ────────────────────────────────────────
public void processOrder(List<OrderItem> items) {
    if (items == null) {
        throw new IllegalArgumentException("Items list cannot be null");
    }
    if (items.isEmpty()) {
        System.out.println("No items to process.");
        return;
    }
    // process items...
    System.out.println("Processing " + items.size() + " items.");
}

Related Topics in Control Statements

while Loop
The while loop is a condition-controlled loop — it continues executing as long as its boolean condition remains true, without specifying in advance how many iterations will occur. It is the natural choice for reading input until end-of-stream, polling until a condition changes, retrying an operation, or any scenario where the termination condition depends on data or events that cannot be predetermined. This entry covers syntax, execution flow, common patterns, infinite loops with controlled exit, and the differences between while and for.
do-while Loop
The do-while loop is Java's only post-test loop — the condition is evaluated after the body executes, which guarantees the body runs at least once regardless of the condition's initial value. This property makes do-while the natural fit for scenarios where the first execution must happen before the first check: menu-driven programs, input validation, digest computation, and game turns. This entry covers syntax, when to use do-while over while, input validation patterns, and the subtle differences that matter in practice.
Enhanced for Loop
The enhanced for loop — also called the for-each loop — was introduced in Java 5 to provide a clean, readable syntax for iterating over arrays and any class that implements Iterable. It eliminates index management and iterator boilerplate entirely. The developer declares what each element is and what to do with it, without concerning themselves with how the iteration mechanism works. This entry covers syntax, the Iterable contract, limitations compared to the indexed loop, modification restrictions, and how for-each maps to iterators under the hood.
break Statement
The break statement immediately terminates the nearest enclosing loop or switch block and transfers control to the first statement after that block. It is one of Java's three jump statements alongside continue and return. break is essential for exiting loops early when a search condition is met, preventing infinite loops from running forever, and stopping switch execution after a matched case.