☕ Java

Java if-else Statement — Syntax, Types, Examples & Best Practices

Everything you need to know about Java if-else — simple if, if-else, if-else-if ladder, nested conditions, ternary operator, pattern matching (Java 16+), anti-patterns, and real-world production code examples.

📅

Last Updated

March 2026

âąī¸

Read Time

22 min

đŸŽ¯

Level

Beginner

đŸˇī¸

Chapter

12 of 35

What is the if-else Statement in Java?

The if-else statement in Java is the most fundamental conditional control flow construct. It allows a program to make decisions — executing one block of code when a condition is true, and optionally executing a different block when it is false. Without if-else, every program would execute statements in a fixed, top-to-bottom sequence, with no ability to branch based on data or user input.

In real-world applications, conditional logic is everywhere: if the user is logged in, show the dashboard; else redirect to login. If the account balance is sufficient, process the payment; else show an error. If the temperature exceeds 100°C, trigger the alarm; else continue monitoring. Every decision your program makes flows through some form of if-else logic.

Java's if-else is strictly boolean-based — the condition must evaluate to either true or false. Unlike C/C++, Java does not allow integer expressions like if(1) or if(count) — this produces a compile-time error. This strictness makes Java code more readable and prevents a common class of bugs.

Simple if Statement — One-Way Selection

The simple if statement is a one-way selection: the body executes only when the condition is true. When the condition is false, the block is skipped entirely and execution moves to the next statement after the if block. No else clause is involved.

📌
Syntax

if (condition) { // statement(s) executed only when condition == true } // execution always continues here

📋
Rules

1. The condition MUST be a boolean expression — int/char/other types cause compile errors. 2. Curly braces {} are optional for single-statement bodies, but always recommended. 3. The condition is evaluated at runtime — any expression returning boolean is valid.

🔁
Flow

Evaluate condition → if TRUE: execute block, then continue → if FALSE: skip block, continue. Either way, program continues after the if statement.

☕ JavaSimpleIf.java
public class SimpleIf {
    public static void main(String[] args) {

        int temperature = 38;

        // ✅ Simple if — executes only when condition is true
        if (temperature > 37) {
            System.out.println("Fever detected! Please consult a doctor.");
        }
        // Execution always reaches here regardless of condition
        System.out.println("Temperature check complete.");

        // ✅ Another example — checking login status
        boolean isLoggedIn = true;
        if (isLoggedIn) {
            System.out.println("Welcome back, User!");
            loadUserPreferences();
        }

        // ✅ Single statement — braces optional (but NOT recommended)
        int age = 20;
        if (age >= 18)
            System.out.println("Eligible to vote."); // Risky — avoid

        // ❌ Compile Error — condition is int, not boolean
        // if (temperature) { }  // ERROR: incompatible types: int cannot be converted to boolean
    }

    static void loadUserPreferences() {
        System.out.println("User preferences loaded.");
    }
}

if-else Statement — Two-Way Selection

The if-else statement provides a two-way selection: when the condition is true, the if block executes; when it is false, the else block executes. Exactly one of the two blocks always runs — never both, never neither. This guarantees complete coverage of all cases.

☕ JavaIfElse.java
public class IfElse {
    public static void main(String[] args) {

        // Example 1: Voting eligibility
        int age = 16;
        if (age >= 18) {
            System.out.println("You are eligible to vote.");
        } else {
            System.out.println("You are not eligible to vote yet.");
            System.out.println("Come back in " + (18 - age) + " year(s).");
        }
        // Output: You are not eligible to vote yet.
        //         Come back in 2 year(s).

        // Example 2: Bank transaction
        double accountBalance = 5000.00;
        double withdrawalAmount = 7500.00;

        if (accountBalance >= withdrawalAmount) {
            accountBalance -= withdrawalAmount;
            System.out.println("Withdrawal successful. New balance: " + accountBalance);
        } else {
            System.out.println("Insufficient funds.");
            System.out.println("Available balance: " + accountBalance);
        }
        // Output: Insufficient funds.
        //         Available balance: 5000.0

        // Example 3: Even or Odd
        int number = 47;
        if (number % 2 == 0) {
            System.out.println(number + " is Even.");
        } else {
            System.out.println(number + " is Odd.");
        }
        // Output: 47 is Odd.
    }
}

if-else-if Ladder — Multi-Way Selection

The if-else-if ladder (also called an else-if chain) tests multiple conditions sequentially from top to bottom. The first condition that evaluates to true has its block executed — all subsequent conditions are then skipped. The optional final else acts as a default case, executing when no condition is true.

☕ JavaIfElseIfLadder.java
public class IfElseIfLadder {
    public static void main(String[] args) {

        // Example 1: Grade Classification
        int marks = 72;

        if (marks >= 90) {
            System.out.println("Grade: A+ (Outstanding)");
        } else if (marks >= 80) {
            System.out.println("Grade: A (Excellent)");
        } else if (marks >= 70) {
            System.out.println("Grade: B (Good)");       // ← This executes
        } else if (marks >= 60) {
            System.out.println("Grade: C (Average)");
        } else if (marks >= 40) {
            System.out.println("Grade: D (Pass)");
        } else {
            System.out.println("Grade: F (Fail)");
        }
        // Output: Grade: B (Good)

        // Example 2: Income Tax Slabs (India - simplified)
        double annualIncome = 850000;

        double taxAmount;
        if (annualIncome <= 300000) {
            taxAmount = 0;
        } else if (annualIncome <= 600000) {
            taxAmount = (annualIncome - 300000) * 0.05;
        } else if (annualIncome <= 900000) {
            taxAmount = 15000 + (annualIncome - 600000) * 0.10;
        } else if (annualIncome <= 1200000) {
            taxAmount = 45000 + (annualIncome - 900000) * 0.15;
        } else if (annualIncome <= 1500000) {
            taxAmount = 90000 + (annualIncome - 1200000) * 0.20;
        } else {
            taxAmount = 150000 + (annualIncome - 1500000) * 0.30;
        }
        System.out.println("Tax payable: ₹" + taxAmount);
        // Output: Tax payable: ₹40000.0
    }
}

Nested if-else — Hierarchical Decision Making

A nested if-else is an if-else statement placed inside the body of another if or else block. This allows decisions that depend on prior decisions — creating a decision tree structure. While powerful, deep nesting quickly becomes difficult to read and maintain — the so-called "arrow code" or "pyramid of doom" anti-pattern.

☕ JavaNestedIfElse.java
public class NestedIfElse {
    public static void main(String[] args) {

        // Example 1: Loan Eligibility
        int age = 28;
        double monthlyIncome = 55000;
        double existingDebt = 10000;
        boolean hasCriminalRecord = false;

        if (age >= 21 && age <= 65) {
            if (monthlyIncome >= 25000) {
                if (!hasCriminalRecord) {
                    if (existingDebt < monthlyIncome * 0.5) {
                        System.out.println("Loan APPROVED ✅");
                    } else {
                        System.out.println("Loan REJECTED — High existing debt");
                    }
                } else {
                    System.out.println("Loan REJECTED — Criminal record found");
                }
            } else {
                System.out.println("Loan REJECTED — Insufficient income");
            }
        } else {
            System.out.println("Loan REJECTED — Age not in eligible range");
        }
        // Output: Loan APPROVED ✅

        // ✅ BETTER: Same logic refactored with Guard Clauses (flat structure)
        System.out.println("--- Refactored with Guard Clauses ---");
        checkLoanEligibility(age, monthlyIncome, existingDebt, hasCriminalRecord);
    }

    // ✅ Guard clause pattern — early return flattens nesting
    static void checkLoanEligibility(int age, double income,
                                      double debt, boolean hasCriminal) {
        if (age < 21 || age > 65) {
            System.out.println("REJECTED — Age not in eligible range");
            return;
        }
        if (income < 25000) {
            System.out.println("REJECTED — Insufficient income");
            return;
        }
        if (hasCriminal) {
            System.out.println("REJECTED — Criminal record found");
            return;
        }
        if (debt >= income * 0.5) {
            System.out.println("REJECTED — High existing debt");
            return;
        }
        System.out.println("Loan APPROVED ✅");
    }
}

Ternary Operator (?:) — Inline if-else

The ternary operator (?:) is Java's only three-operand operator. It is a compact, inline replacement for simple if-else statements that assign a value. Syntax: variable = (condition) ? valueIfTrue : valueIfFalse;. The name 'ternary' comes from Latin ternarius meaning 'consisting of three' — it takes three operands: a condition, a true-value, and a false-value.

☕ JavaTernaryOperator.java
public class TernaryOperator {
    public static void main(String[] args) {

        // Basic if-else vs ternary comparison
        int age = 20;

        // ❌ Verbose: 5 lines for a simple assignment
        String status;
        if (age >= 18) {
            status = "Adult";
        } else {
            status = "Minor";
        }

        // ✅ Ternary: 1 clean line
        String statusTernary = (age >= 18) ? "Adult" : "Minor";
        System.out.println(statusTernary); // Output: Adult

        // ✅ Ternary in print statement
        int number = -7;
        System.out.println(number + " is " + (number >= 0 ? "positive" : "negative"));
        // Output: -7 is negative

        // ✅ Ternary for null-safe default values
        String username = null;
        String displayName = (username != null) ? username : "Guest";
        System.out.println("Hello, " + displayName); // Output: Hello, Guest

        // ✅ Ternary with method calls
        double price = 1500.0;
        double discount = (price > 1000) ? price * 0.10 : price * 0.05;
        System.out.println("Discount: ₹" + discount); // Output: Discount: ₹150.0

        // ❌ BAD: Nested ternary — avoid at all costs
        int marks = 75;
        String grade = (marks >= 90) ? "A" : (marks >= 70) ? "B" : (marks >= 50) ? "C" : "F";
        // This compiles but is extremely hard to read — use if-else-if ladder instead

        // ✅ GOOD: Use ternary ONLY for simple, flat conditions
        int temperature = 35;
        String weather = (temperature > 30) ? "Hot" : "Pleasant";
        System.out.println("Weather: " + weather); // Output: Weather: Hot
    }
}
Aspectif-elseTernary (?:)
PurposeGeneral conditional branchingInline value selection only
Returns a value?No — it's a statementYes — it's an expression
Side effects OK?Yes — any statements insidePossible but strongly discouraged
ReadabilityHigh — clear for complex logicHigh only for simple, flat conditions
NestingAcceptable up to 2-3 levelsAvoid nested ternary entirely
Multiple statementsYes — {} can contain many statementsNo — each branch must be a single expression
Use caseComplex logic, multiple statements, side effectsSimple value assignment: x = a ? b : c
Java versionSince Java 1.0Since Java 1.0

if-else vs switch — When to Use Which

Both if-else and switch are conditional control flow structures, but they serve different purposes. Choosing the right one makes your code more readable and in some cases more performant. Java 14+ switch expressions and Java 21 pattern matching switch have significantly expanded switch's capabilities.

Criteriaif-elseswitch
Condition typeAny boolean expressionSingle variable: int, char, String, enum, sealed classes (Java 21)
Range checks✅ Perfect — if (age > 18 && age < 60)❌ Not suitable — can't check ranges natively
Equality checks (many)âš ī¸ Works but verbose✅ Cleaner — each case is one value
Null handling✅ Explicit null checkâš ī¸ null causes NullPointerException (Java < 21)
Multiple conditions (&&)✅ Fully supported❌ Not applicable
Performance (many cases)O(n) — evaluates top to bottomO(1) — jump table optimization by JVM
Fall-through❌ Not applicableâš ī¸ Yes, by default — need break or yield
Pattern matching✅ instanceof pattern (Java 16+)✅ switch pattern matching (Java 21)
Readability (2-3 cases)✅ Clear✅ Clear
Readability (10+ cases)❌ Ladder becomes hard to scan✅ Much cleaner
☕ JavaIfElseVsSwitch.java
// Scenario: Display day type based on day number

// ❌ if-else — verbose for exact-match comparison
int day = 3;
String dayType;
if (day == 1 || day == 7) {
    dayType = "Weekend";
} else if (day == 2 || day == 3 || day == 4 || day == 5 || day == 6) {
    dayType = "Weekday";
} else {
    dayType = "Invalid day";
}

// ✅ switch expression (Java 14+) — clean and expressive
String dayTypeSwitch = switch (day) {
    case 1, 7 -> "Weekend";
    case 2, 3, 4, 5, 6 -> "Weekday";
    default -> "Invalid day";
};

// Use if-else for range checks — switch can't do this
double bmi = 24.5;
String bmiCategory;
if (bmi < 18.5) {
    bmiCategory = "Underweight";
} else if (bmi < 25.0) {
    bmiCategory = "Normal weight";  // ← matches
} else if (bmi < 30.0) {
    bmiCategory = "Overweight";
} else {
    bmiCategory = "Obese";
}
System.out.println("BMI Category: " + bmiCategory);

Boolean Conditions in Depth — Writing Effective Conditions

The power of if-else depends entirely on the quality of its boolean condition expression. Java supports rich condition building using relational operators, logical operators, short-circuit evaluation, and method calls. Understanding these deeply prevents bugs and enables concise, correct conditions.

đŸ”ĸ
Relational Operators

== (equal), != (not equal), > (greater), < (less), >= (greater or equal), <= (less or equal). WARNING: Use == for primitive types only. For objects (String, Integer, etc.), == checks reference equality (same memory address), not value equality. Always use .equals() for object content comparison: str.equals("hello") not str == "hello".

🔗
Logical Operators — && and ||

&& (AND): true only if BOTH sides are true. Short-circuits — right side NOT evaluated if left is false. || (OR): true if EITHER side is true. Short-circuits — right side NOT evaluated if left is true. Use short-circuit evaluation strategically: put cheaper/more likely conditions on the LEFT.

❗
Logical NOT — !

! (NOT): inverts a boolean. !true = false, !false = true. Prefer positive conditions over negative when possible: 'if (isActive)' is clearer than 'if (!isInactive)'. Double negation (!!isActive) is always code smell — simplify to (isActive). De Morgan's laws: !(A && B) = !A || !B, and !(A || B) = !A && !B.

⚡
Short-Circuit Evaluation

Java's && and || use short-circuit evaluation. In 'if (obj != null && obj.isActive())', if obj is null, the second condition is NEVER evaluated (no NullPointerException). In 'if (list == null || list.isEmpty())', if list is null, isEmpty() is never called. Always put null checks and cheap checks FIRST in compound conditions.

đŸŽ¯
instanceof Operator

Tests whether an object is an instance of a class: if (shape instanceof Circle). Java 16+ adds Pattern Matching: if (shape instanceof Circle c) — this both tests AND casts in one expression, eliminating explicit casting. Java 21 extends this to switch statements for sealed hierarchies.

📊
Method Call Conditions

Any method returning boolean can be a condition: if (user.isActive()), if (list.isEmpty()), if (str.contains("@")), if (file.exists()). This enables highly readable, self-documenting conditions. Prefer boolean-returning methods over manual flag variables: 'if (account.hasInsufficientFunds())' vs 'if (balance < amount)'.

☕ JavaConditionExpressions.java
import java.util.List;

public class ConditionExpressions {
    public static void main(String[] args) {

        // ✅ == for primitives, .equals() for objects
        int a = 5, b = 5;
        if (a == b) System.out.println("Primitive == works correctly");

        String s1 = new String("hello");
        String s2 = new String("hello");
        if (s1.equals(s2)) System.out.println("String equals() — content match ✅");
        if (s1 == s2)      System.out.println("This won't print — different objects ❌");

        // ✅ Short-circuit: null-safe chaining
        String username = null;
        if (username != null && username.length() > 3) {
            System.out.println("Username is valid");
        } else {
            System.out.println("Username is null or too short"); // ← prints
        }

        // ✅ Compound conditions
        int age = 25;
        double income = 60000;
        boolean hasGoodCreditScore = true;

        if (age >= 21 && income >= 30000 && hasGoodCreditScore) {
            System.out.println("Pre-approved for credit card");
        }

        // ✅ instanceof with Pattern Matching (Java 16+)
        Object obj = "Hello, Java!";
        if (obj instanceof String str) {  // No explicit cast needed
            System.out.println("String length: " + str.length()); // str is already String
        }

        // ✅ Boolean method conditions — most readable
        List<String> errors = List.of();
        if (errors.isEmpty()) {
            System.out.println("No errors — proceeding");
        }
    }
}

Common Mistakes & Pitfalls — Bugs That Fool Everyone

These mistakes are consistently found in Java beginner code, often pass code review unnoticed, and cause subtle runtime bugs. Study each one carefully — recognizing these patterns in your own code is a key skill.

☕ JavaCommonMistakes.java
// ❌ MISTAKE 1: Assignment instead of comparison (= instead of ==)
// In Java this is a COMPILE ERROR (unlike C/C++ where it's a silent bug)
// int x = 5;
// if (x = 10) { }  // ERROR: incompatible types: int cannot be converted to boolean

// ❌ MISTAKE 2: String comparison with == (reference, not value)
String input = new String("yes");
if (input == "yes") {   // ❌ FALSE — different objects in memory
    System.out.println("User confirmed"); // Never prints!
}
if (input.equals("yes")) {  // ✅ TRUE — compares content
    System.out.println("User confirmed"); // Prints correctly
}

// ❌ MISTAKE 3: Missing braces causing logic error
boolean isAdmin = false;
boolean isLoggedIn = true;
if (isAdmin)                              // Only this line is conditional
    System.out.println("Admin panel");   // Only executes when isAdmin=true
    System.out.println("Logout button"); // ❌ ALWAYS executes — not inside if!

// ❌ MISTAKE 4: Checking boolean with == true (redundant)
boolean isActive = true;
if (isActive == true) { }  // ❌ Redundant — boolean IS the condition
if (isActive) { }          // ✅ Direct and clean
if (isActive == false) { } // ❌ Redundant
if (!isActive) { }         // ✅ Use NOT operator

// ❌ MISTAKE 5: Unreachable else due to wrong condition order
int score = 95;
if (score >= 40) {
    System.out.println("Pass");        // Always matches first!
} else if (score >= 90) {
    System.out.println("Distinction"); // ❌ NEVER reached — 95>=40 already matched
}
// ✅ Fix: More specific condition first
if (score >= 90) {
    System.out.println("Distinction"); // ✅ Now correctly matches 95
} else if (score >= 40) {
    System.out.println("Pass");
}

// ❌ MISTAKE 6: NullPointerException from reversed equals call
String status = null;
// if (status.equals("ACTIVE")) { }    // ❌ NPE — status is null!
if ("ACTIVE".equals(status)) { }       // ✅ Literal first — null-safe
if (status != null && status.equals("ACTIVE")) { } // ✅ Also correct

Pattern Matching with instanceof — Java 16+ Feature

Java 16 introduced Pattern Matching for instanceof (JEP 394) — a major quality-of-life improvement that eliminates the verbose cast-after-check pattern. Instead of testing type with instanceof and then separately casting, you can do both in a single expression. The binding variable is only in scope where the pattern is guaranteed to match.

☕ JavaPatternMatchingIf.java
// Before Java 16 — verbose test-and-cast pattern
Object shape = new Circle(5.0);

// ❌ Old way: 3 steps — test, cast, use
if (shape instanceof Circle) {
    Circle c = (Circle) shape;   // Redundant cast
    System.out.println("Area: " + c.calculateArea());
}

// ✅ Java 16+ Pattern Matching: test + bind in one step
if (shape instanceof Circle c) {
    // 'c' is automatically a Circle here — no cast needed
    System.out.println("Area: " + c.calculateArea());
}

// ✅ With condition on the bound variable (Java 16+)
if (shape instanceof Circle c && c.getRadius() > 3.0) {
    System.out.println("Large circle with area: " + c.calculateArea());
}

// ✅ Polymorphic method using pattern matching
static double calculateArea(Object shape) {
    if (shape instanceof Circle c) {
        return Math.PI * c.getRadius() * c.getRadius();
    } else if (shape instanceof Rectangle r) {
        return r.getWidth() * r.getHeight();
    } else if (shape instanceof Triangle t) {
        return 0.5 * t.getBase() * t.getHeight();
    } else {
        throw new IllegalArgumentException("Unknown shape: " + shape);
    }
}

// ✅ Java 21: Same logic, cleaner with switch pattern matching
static double calculateAreaSwitch(Object shape) {
    return switch (shape) {
        case Circle c    -> Math.PI * c.getRadius() * c.getRadius();
        case Rectangle r -> r.getWidth() * r.getHeight();
        case Triangle t  -> 0.5 * t.getBase() * t.getHeight();
        default          -> throw new IllegalArgumentException("Unknown: " + shape);
    };
}

Bad Practices & Anti-Patterns — What Senior Developers Reject

These if-else anti-patterns are the most common reasons for failed code reviews in professional Java teams. Each pattern either reduces readability, increases complexity, or introduces subtle bugs.

đŸšĢ
Deeply Nested if-else (Arrow Code)

Code that indents right as it grows — 4, 5, 6 levels deep — is called 'arrow code' and is virtually unreadable. Refactor using: (1) Guard clauses with early return, (2) Extract method — move nested logic to a private method, (3) Replace conditionals with polymorphism (OOP). Rule of thumb: more than 3 levels of nesting is a red flag.

đŸšĢ
God-Condition (Overloaded boolean expression)

A condition like 'if (a && b && !c || d && (e || f) && !g)' is a maintenance nightmare. Break complex conditions into named boolean variables or extracted methods: 'boolean isEligible = isAdult && hasIncome && !isBlacklisted;' then 'if (isEligible && hasSufficientDocuments)'. Named conditions serve as inline documentation.

đŸšĢ
Returning boolean literals from if-else

Writing 'if (condition) { return true; } else { return false; }' is redundant. The condition IS the boolean value. Simply: 'return condition;'. Similarly, 'if (x > 5) { flag = true; } else { flag = false; }' should be: 'flag = (x > 5);'. This is one of the most common beginner redundancies.

đŸšĢ
Using if-else where switch is cleaner

When you're checking one variable against 5+ discrete values, an if-else-if ladder becomes visually cluttered. A switch statement (especially Java 14+ switch expression with arrow syntax) is dramatically cleaner. If-else should be reserved for range checks, compound boolean conditions, and null handling.

đŸšĢ
Negative Condition First (Inverted Logic)

Writing the else-path first: 'if (!isValid) { handleError(); } else { processSuccess(); }' forces readers to mentally invert the logic. Put the HAPPY PATH (normal case) first, exception/error handling in else. Positive conditions are cognitively easier: 'if (isValid) { processSuccess(); } else { handleError(); }'.

đŸšĢ
Empty if or else blocks

An empty if block: 'if (condition) { } else { doSomething(); }' — just negate the condition: 'if (!condition) { doSomething(); }'. An empty else block: 'if (condition) { doSomething(); } else { }' — remove the empty else entirely. Empty blocks suggest incomplete logic or confusion about the intent.

☕ JavaIfElseAntiPatterns.java
// ❌ ANTI-PATTERN 1: Returning boolean literal
public boolean isAdult(int age) {
    if (age >= 18) {
        return true;   // ❌ Redundant
    } else {
        return false;  // ❌ Redundant
    }
}
// ✅ BETTER: Return the condition directly
public boolean isAdult(int age) {
    return age >= 18;
}

// ❌ ANTI-PATTERN 2: Overloaded god-condition
if (user != null && user.isActive() && !user.isBanned()
        && user.getRole() != null && user.getRole().hasPermission("EDIT")
        && (user.getSubscriptionLevel() == 2 || user.getSubscriptionLevel() == 3)) {
    allowEdit();
}

// ✅ BETTER: Named boolean variables as documentation
boolean isValidUser      = user != null && user.isActive() && !user.isBanned();
boolean hasEditPermission = user.getRole() != null
                           && user.getRole().hasPermission("EDIT");
boolean hasPremiumAccess  = user.getSubscriptionLevel() >= 2;
if (isValidUser && hasEditPermission && hasPremiumAccess) {
    allowEdit();
}

// ❌ ANTI-PATTERN 3: Inverted logic (error path first)
if (!isAuthenticated) {
    redirectToLogin();
} else {
    loadDashboard();
}
// ✅ BETTER: Happy path first
if (isAuthenticated) {
    loadDashboard();
} else {
    redirectToLogin();
}

Real-World Production Code Examples — if-else in Context

The following examples model if-else usage in real enterprise Java codebases — Spring Boot application patterns with idiomatic conditional logic at each layer.

☕ JavaPaymentProcessor.java — Production-Grade if-else Usage
package com.techsustainify.payment.service;

public class PaymentProcessor {

    private static final double MAX_TRANSACTION_LIMIT = 100000.00;
    private static final int    MAX_RETRY_ATTEMPTS    = 3;

    /**
     * Processes a payment with full validation using guard clauses.
     * Guard clause pattern: validate early, return early, happy path last.
     */
    public PaymentResult processPayment(PaymentRequest request, UserAccount user) {

        // Guard clause 1: Null check
        if (request == null) {
            return PaymentResult.failure("Payment request cannot be null");
        }

        // Guard clause 2: Account status
        if (!user.isAccountActive()) {
            return PaymentResult.failure("Account is suspended or inactive");
        }

        // Guard clause 3: Amount validation
        if (request.getAmount() <= 0) {
            return PaymentResult.failure("Payment amount must be positive");
        }

        // Guard clause 4: Transaction limit
        if (request.getAmount() > MAX_TRANSACTION_LIMIT) {
            return PaymentResult.failure("Amount exceeds transaction limit of ₹" + MAX_TRANSACTION_LIMIT);
        }

        // Guard clause 5: Sufficient balance
        if (user.getBalance() < request.getAmount()) {
            return PaymentResult.failure("Insufficient balance. Available: ₹" + user.getBalance());
        }

        // Happy path: all validations passed
        // Apply discount if eligible
        double finalAmount = request.getAmount();
        if (user.isPremiumMember() && request.getAmount() > 5000) {
            finalAmount = finalAmount * 0.95; // 5% premium discount
        }

        // Choose payment gateway based on amount
        PaymentGateway gateway;
        if (finalAmount <= 2000) {
            gateway = PaymentGateway.UPI;
        } else if (finalAmount <= 50000) {
            gateway = PaymentGateway.NETBANKING;
        } else {
            gateway = PaymentGateway.RTGS;
        }

        return executeWithRetry(request, user, finalAmount, gateway);
    }

    private PaymentResult executeWithRetry(PaymentRequest request, UserAccount user,
                                            double amount, PaymentGateway gateway) {
        int attempts = 0;
        PaymentResult result = null;

        while (attempts < MAX_RETRY_ATTEMPTS) {
            result = gateway.execute(request, amount);
            if (result.isSuccess()) {
                user.deductBalance(amount);
                return result;
            }
            attempts++;
        }

        return PaymentResult.failure("Payment failed after " + MAX_RETRY_ATTEMPTS + " attempts");
    }
}
☕ JavaUserValidator.java — Validation with if-else
package com.techsustainify.user.validation;

import java.util.ArrayList;
import java.util.List;

public class UserValidator {

    private static final int MIN_PASSWORD_LENGTH = 8;
    private static final int MAX_USERNAME_LENGTH = 30;

    public ValidationResult validateRegistration(UserRegistrationRequest req) {
        List<String> errors = new ArrayList<>();

        // Validate username
        if (req.getUsername() == null || req.getUsername().isBlank()) {
            errors.add("Username is required");
        } else if (req.getUsername().length() > MAX_USERNAME_LENGTH) {
            errors.add("Username must not exceed " + MAX_USERNAME_LENGTH + " characters");
        } else if (!req.getUsername().matches("^[a-zA-Z0-9_]+$")) {
            errors.add("Username can only contain letters, digits, and underscores");
        }

        // Validate email
        if (req.getEmail() == null || req.getEmail().isBlank()) {
            errors.add("Email address is required");
        } else if (!req.getEmail().contains("@") || !req.getEmail().contains(".")) {
            errors.add("Please enter a valid email address");
        }

        // Validate password
        if (req.getPassword() == null || req.getPassword().length() < MIN_PASSWORD_LENGTH) {
            errors.add("Password must be at least " + MIN_PASSWORD_LENGTH + " characters");
        } else if (!req.getPassword().matches(".*[A-Z].*")) {
            errors.add("Password must contain at least one uppercase letter");
        } else if (!req.getPassword().matches(".*[0-9].*")) {
            errors.add("Password must contain at least one digit");
        }

        // Validate age
        if (req.getAge() < 13) {
            errors.add("You must be at least 13 years old to register");
        } else if (req.getAge() > 120) {
            errors.add("Please enter a valid age");
        }

        return errors.isEmpty()
            ? ValidationResult.success()
            : ValidationResult.failure(errors);
    }
}

if-else Flowchart — Visual Decision Flow

These flowcharts show the execution paths for each type of if-else construct in Java.

â–ļ Program reaches if statement
Enter if
🔍 Evaluate conditionboolean expression → true or false
TRUE
✅ Execute IF blockcondition was true
After if block
â†Šī¸ Execute ELSE blockcondition was false (if else exists)
After else block
âžĄī¸ Continue executionstatement after if-else

Code Execution Flow — from source to output

Java if-else Interview Questions — Beginner to Advanced

These questions are consistently asked in Java fresher interviews, OCPJP/OCA certification exams, and campus placement tests.

Practice Questions — Test Your if-else Knowledge

Challenge yourself with these practice questions. Attempt each independently before reading the answer — active recall is proven to be 2–3x more effective than passive reading.

1. What is the output of the following code? int x = 15; if (x > 10) System.out.println("Greater than 10"); System.out.println("This always prints"); if (x > 20) System.out.println("Greater than 20"); System.out.println("Done");

Easy

2. Rewrite using ternary operator: String result; if (score >= 50) { result = "PASS"; } else { result = "FAIL"; }

Easy

3. Find and fix the bug: String input = getUserInput(); if (input == "quit") { System.out.println("Exiting..."); System.exit(0); }

Easy

4. Refactor this nested code using guard clauses: public void processOrder(Order order) { if (order != null) { if (order.isConfirmed()) { if (order.getItems().size() > 0) { if (order.getPaymentStatus() == PAID) { shipOrder(order); } } } } }

Medium

5. What is the output? int a = 5, b = 3; if (a > b) if (a > 10) System.out.println("A"); else System.out.println("B"); System.out.println("C");

Medium

6. Simplify this code: public boolean isEligibleForDiscount(Customer c) { if (c.isPremium() == true) { if (c.getAge() >= 60 || c.getAge() <= 25) { return true; } else { return false; } } else { return false; } }

Medium

7. Using Java 16+ pattern matching, rewrite: Object obj = getShape(); if (obj instanceof Rectangle) { Rectangle r = (Rectangle) obj; System.out.println(r.getWidth() * r.getHeight()); } else if (obj instanceof Circle) { Circle c = (Circle) obj; System.out.println(Math.PI * c.getRadius() * c.getRadius()); }

Medium

8. Will this compile? What is its output? boolean flag = false; if (flag = true) { System.out.println("Yes"); } else { System.out.println("No"); }

Hard

Conclusion — if-else: The Decision Engine of Every Java Program

The if-else statement is the heartbeat of program logic. Every meaningful program makes decisions — checking user permissions, validating inputs, branching on data values, handling errors. All of these flow through if-else constructs. Mastering if-else is not just about syntax — it is about writing clear, correct, and maintainable conditional logic.

The difference between a junior and senior Java developer is often visible in how they use conditionals. Junior code has deeply nested arrow code, redundant boolean literals, missing braces, and == for String comparison. Senior code uses guard clauses, named conditions, .equals() consistently, appropriate ternary, and Java 16+ pattern matching where it improves clarity.

ConstructUse CaseExample
Simple ifExecute only when true — no else neededif (isNewUser) sendWelcome();
if-elseTwo-way branch — either A or B, never bothif (balance >= amount) {...} else {...}
if-else-if ladderMulti-way branch — first match winsif (marks >= 90) ... else if (marks >= 70) ...
Nested if-elseHierarchical decisions — prefer guard clausesif (loggedIn) { if (admin) {...} }
Ternary ?:Inline value assignment — simple conditions onlyString s = age >= 18 ? "Adult" : "Minor";
Pattern matching instanceofType-test + bind — Java 16+if (obj instanceof Circle c) { c.area(); }
Guard clause (early return)Flatten nesting — handle errors firstif (input == null) return; ... doWork();

Your next step: Java switch Statement — where you'll see how Java provides an alternative to if-else-if ladders for multi-way branching, and how the modern switch expression (Java 14+) and pattern matching switch (Java 21) make it even more powerful. ☕

Frequently Asked Questions — Java if-else