Control Flow

Java If-Else Statement

Master conditional logic in Java — if, else, else-if, nested conditions, and the ternary operator with real-world examples.

What is an If-Else Statement?

The if-else statement allows your program to make decisions — execute different blocks of code based on whether a condition is true or false.

java
if (condition) {
    // Executes when condition is TRUE
} else {
    // Executes when condition is FALSE
}

This is the foundation of all programming logic. Without conditions, programs would always execute the same code regardless of input.

The if Statement

The simplest form — executes a block only if the condition is true:

java
public class IfDemo {
    public static void main(String[] args) {
        int age = 20;

        if (age >= 18) {
            System.out.println("You are eligible to vote.");
        }

        System.out.println("Program continues...");
    }
}

Output:

You are eligible to vote.
Program continues...

If age were 15, the if block would be skipped and only "Program continues..." would print.

The if-else Statement

Provides an alternative path when the condition is false:

java
public class IfElseDemo {
    public static void main(String[] args) {
        int temperature = 35;

        if (temperature > 30) {
            System.out.println("It's a hot day. Stay hydrated! ☀️");
        } else {
            System.out.println("The weather is pleasant. Enjoy! 🌤️");
        }
    }
}

Output:

It's a hot day. Stay hydrated! ☀️

The if-else-if Ladder

When you have multiple conditions to check:

java
public class GradeCalculator {
    public static void main(String[] args) {
        int marks = 78;
        char grade;

        if (marks >= 90) {
            grade = 'A';
        } else if (marks >= 80) {
            grade = 'B';
        } else if (marks >= 70) {
            grade = 'C';
        } else if (marks >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }

        System.out.println("Marks: " + marks);
        System.out.println("Grade: " + grade);
    }
}

Output:

Marks: 78
Grade: C

How it works:

Conditionmarks = 78Result
marks >= 9078 >= 90? falseSkip
marks >= 8078 >= 80? falseSkip
marks >= 7078 >= 70? true✓ Execute this block
(remaining)Not checked

Important: Once a condition is true, its block executes and the remaining conditions are skipped entirely.

Nested If-Else

You can place if-else statements inside other if-else blocks:

java
public class NestedIfDemo {
    public static void main(String[] args) {
        int age = 25;
        boolean hasLicense = true;

        if (age >= 18) {
            if (hasLicense) {
                System.out.println("You can drive a car.");
            } else {
                System.out.println("You are old enough, but you need a license.");
            }
        } else {
            System.out.println("You are not old enough to drive.");
        }
    }
}

Output:

You can drive a car.

Tip: Avoid deep nesting (more than 2-3 levels). Refactor into methods or use logical operators instead.

Logical Operators in Conditions

Combine multiple conditions using logical operators:

OperatorNameDescription
&&ANDBoth conditions must be true
||ORAt least one condition must be true
!NOTReverses the condition
java
public class LogicalDemo {
    public static void main(String[] args) {
        int age = 25;
        boolean hasLicense = true;
        boolean hasInsurance = false;

        // AND — all must be true
        if (age >= 18 && hasLicense) {
            System.out.println("Can drive: Yes");
        }

        // OR — at least one must be true
        if (hasLicense || hasInsurance) {
            System.out.println("Has at least one document: Yes");
        }

        // NOT — reverses condition
        if (!hasInsurance) {
            System.out.println("Warning: No insurance!");
        }
    }
}

Output:

Can drive: Yes
Has at least one document: Yes
Warning: No insurance!

Nested if vs Logical AND

These two are equivalent:

java
// Nested if
if (age >= 18) {
    if (hasLicense) {
        System.out.println("Can drive");
    }
}

// Logical AND (cleaner)
if (age >= 18 && hasLicense) {
    System.out.println("Can drive");
}

Ternary Operator (Short If-Else)

For simple if-else assignments, use the ternary operator:

java
// Syntax: variable = (condition) ? valueIfTrue : valueIfFalse;

int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status);  // Adult

// Equivalent to:
String status2;
if (age >= 18) {
    status2 = "Adult";
} else {
    status2 = "Minor";
}

Nested Ternary (use sparingly)

java
int marks = 85;
String grade = (marks >= 90) ? "A" :
               (marks >= 80) ? "B" :
               (marks >= 70) ? "C" : "F";
System.out.println(grade);  // B

Warning: Nested ternary operators reduce readability. Use if-else-if for complex conditions.

Common Comparison Operators

OperatorMeaningExample
==Equal tox == 10
!=Not equal tox != 10
>Greater thanx > 10
<Less thanx < 10
>=Greater than or equalx >= 10
<=Less than or equalx <= 10

Comparing Strings

java
String name = "Java";

// ✗ WRONG — compares references, not values
if (name == "Java") { ... }

// ✓ CORRECT — compares actual content
if (name.equals("Java")) {
    System.out.println("Match!");
}

// Case-insensitive comparison
if (name.equalsIgnoreCase("java")) {
    System.out.println("Case-insensitive match!");
}

Practical Example: ATM Withdrawal

java
import java.util.Scanner;

public class ATMWithdrawal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double balance = 25000.0;
        double minBalance = 500.0;

        System.out.printf("Current Balance: ₹%.2f%n", balance);
        System.out.print("Enter withdrawal amount: ₹");
        double amount = scanner.nextDouble();

        if (amount <= 0) {
            System.out.println("❌ Invalid amount. Please enter a positive number.");
        } else if (amount > balance - minBalance) {
            System.out.printf("❌ Insufficient funds. Maximum withdrawal: ₹%.2f%n",
                             balance - minBalance);
        } else if (amount % 100 != 0) {
            System.out.println("❌ Amount must be a multiple of ₹100.");
        } else {
            balance -= amount;
            System.out.printf("✅ ₹%.2f withdrawn successfully.%n", amount);
            System.out.printf("   Remaining Balance: ₹%.2f%n", balance);
        }

        scanner.close();
    }
}

Sample Output:

Current Balance: ₹25000.00
Enter withdrawal amount: ₹5000
✅ ₹5000.00 withdrawn successfully.
   Remaining Balance: ₹20000.00

Common Mistakes

1. Using = instead of ==

java
int x = 5;
// if (x = 10)  // ✗ Assignment, not comparison — compile error
if (x == 10)    // ✓ Correct comparison

2. Missing Braces

java
// Dangerous — only the first line is part of the if
if (age > 18)
    System.out.println("Adult");
    System.out.println("Can vote");  // Always executes!

// Safe — always use braces
if (age > 18) {
    System.out.println("Adult");
    System.out.println("Can vote");
}

3. Comparing Strings with ==

java
String input = new String("hello");
// if (input == "hello")        // ✗ May return false
if (input.equals("hello"))      // ✓ Always correct

Summary

  • if executes code when a condition is true
  • if-else provides an alternative path for when the condition is false
  • if-else-if ladder checks multiple conditions in sequence
  • Use logical operators (&&, ||, !) to combine conditions
  • The ternary operator (? :) is a shorthand for simple if-else
  • Always compare Strings with .equals(), not ==
  • Always use curly braces even for single-line if blocks
  • Avoid deep nesting — refactor into methods or use logical operators