☕ 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

Control Statements
Control statements determine the flow of execution in a Java program. Without them, code executes line by line from top to bottom. Control statements allow the program to make decisions, repeat actions, and jump to different parts of the code based on conditions. Java provides three categories: selection statements (if, if-else, switch), iteration statements (for, while, do-while), and jump statements (break, continue, return).
if-else Statement
The if-else statement extends the basic if by providing an alternative block that executes when the condition is false. It guarantees that exactly one of two blocks always executes — either the if block (condition true) or the else block (condition false). The if-else-if chain extends this to choose among more than two alternatives.
Nested if
A nested if is an if statement placed inside the body of another if or else block. Nesting allows multi-level decision making — first check a broad condition, then refine with a more specific condition inside it. While nesting is sometimes necessary, deep nesting quickly reduces readability and should be refactored using guard clauses, logical operators, or extracted methods.
switch Statement
The switch statement selects one of several code blocks to execute based on the value of a single expression. It is a cleaner alternative to a long if-else-if chain when choosing among multiple constant values. Java switch works with byte, short, int, char, String, and enum types. Each case label must be a compile-time constant and the optional default case handles all unmatched values.