Java if-else Statements

Learn how to make your program choose between two different paths. Use if-else to run different code based on whether a condition is true or false.

What is an if-else Statement?

An if-else statement lets your program make a choice between two options. It checks if something is true, and if it is, it runs one block of code. If it's false, it runs a different block of code. One of the two blocks ALWAYS runs - never both, and never neither.

  • if part: Checks a condition (true or false)
  • else part: Runs if the if condition is false
  • Exactly one block runs: Either the if block OR the else block, never both
  • Perfect for opposites: Yes or No, Adult or Child, Pass or Fail

Think of it this way: if-else is like a fork in the road. At the fork, you check a sign (the condition). The sign either says true or false, and you take the road that matches what the sign says. You only walk one road, not both.

Basic if-else Syntax

Here's the structure of a simple if-else statement:

Syntax Structure


if (condition) {
    // This block runs if condition is true
    // Put your code here
} else {
    // This block runs if condition is false
    // Put your code here
}

Breakdown:

  • if - The keyword that starts a conditional
  • (condition) - A test that is either true or false
  • {} - Curly braces contain the code to run
  • else - Provides the alternative when if is false

Simple if-else Examples

Let's see if-else in action with real, easy-to-understand examples:

Example 1: Checking Age (Adult or Minor)


public class AgeCheck {
    public static void main(String[] args) {
        int age = 20;
        
        if (age >= 18) {
            System.out.println("You are an adult!");
        } else {
            System.out.println("You are a minor.");
        }
    }
}
Output:
You are an adult!

How it works:

  • Check: Is age >= 18? YES, it's 20
  • Since the condition is true, the if block runs
  • The else block is completely skipped
  • Output: "You are an adult!"

Example 2: Checking Age (When condition is false)


public class AgeCheck2 {
    public static void main(String[] args) {
        int age = 14;
        
        if (age >= 18) {
            System.out.println("You are an adult!");
        } else {
            System.out.println("You are a minor.");
        }
    }
}
Output:
You are a minor.

How it works:

  • Check: Is age >= 18? NO, it's only 14
  • Since the condition is false, the if block is skipped
  • The else block runs instead
  • Output: "You are a minor."

More Practical Examples

Example 3: Checking Exam Result (Pass or Fail)


public class ExamResult {
    public static void main(String[] args) {
        int marks = 65;
        int passingMarks = 50;
        
        if (marks >= passingMarks) {
            System.out.println("Congratulations! You passed!");
            System.out.println("Your marks: " + marks);
        } else {
            System.out.println("Sorry, you failed.");
            System.out.println("Passing marks needed: " + passingMarks);
        }
    }
}
Output:
Congratulations! You passed!
Your marks: 65

Example 4: Checking Temperature (Hot or Cold)


public class TemperatureCheck {
    public static void main(String[] args) {
        double temperature = 28;
        
        if (temperature > 25) {
            System.out.println("It's hot outside!");
            System.out.println("Don't forget sunscreen and water.");
        } else {
            System.out.println("It's cool outside.");
            System.out.println("You can wear a sweater.");
        }
    }
}
Output:
It's hot outside!
Don't forget sunscreen and water.

Example 5: Comparing Strings (Equal or Not)


public class PasswordCheck {
    public static void main(String[] args) {
        String correctPassword = "Java123";
        String enteredPassword = "Java123";
        
        if (enteredPassword.equals(correctPassword)) {
            System.out.println("Password correct! Login successful.");
        } else {
            System.out.println("Password incorrect. Try again.");
        }
    }
}
Output:
Password correct! Login successful.

Key Point: Notice that you can put multiple lines of code inside the if and else blocks. Just make sure they're all between the curly braces {}.

Using Different Comparison Operators

The condition in if-else can use many different operators to compare values:

Example: Different Comparison Operators


public class ComparisonOperators {
    public static void main(String[] args) {
        // Greater than (>)
        int score = 95;
        if (score > 90) {
            System.out.println("Excellent score!");
        } else {
            System.out.println("Good score!");
        }
        
        // Less than (<)
        int items = 5;
        if (items < 10) {
            System.out.println("In stock");
        } else {
            System.out.println("Low stock warning");
        }
        
        // Equal to (==)
        int code = 4;
        if (code == 4) {
            System.out.println("Code verified!");
        } else {
            System.out.println("Invalid code");
        }
        
        // Not equal to (!=)
        String status = "active";
        if (status != "inactive") {
            System.out.println("User is active");
        } else {
            System.out.println("User is inactive");
        }
        
        // Greater than or equal to (>=)
        int age = 18;
        if (age >= 18) {
            System.out.println("Can vote");
        } else {
            System.out.println("Too young to vote");
        }
    }
}
Output:
Excellent score!
In stock
Code verified!
User is active
Can vote

Comparison Operators Used:

  • > Greater than: Is the first number bigger?
  • < Less than: Is the first number smaller?
  • == Equal to: Are they exactly the same?
  • != Not equal to: Are they different?
  • >= Greater or equal: Is it bigger or same?
  • <= Less or equal: Is it smaller or same?

Combining Conditions with && and ||

Sometimes you need to check multiple conditions at once. Use && (AND) when all conditions must be true, and || (OR) when at least one must be true.

Example 1: Using && (AND) - All Conditions Must Be True


public class AndOperator {
    public static void main(String[] args) {
        int age = 20;
        boolean hasLicense = true;
        
        if (age >= 18 && hasLicense) {
            System.out.println("You can drive a car!");
        } else {
            System.out.println("You cannot drive yet.");
        }
        
        // Another example
        int score = 85;
        int attendance = 92;
        if (score >= 80 && attendance >= 90) {
            System.out.println("Eligible for scholarship!");
        } else {
            System.out.println("Not eligible for scholarship.");
        }
    }
}
Output:
You can drive a car!
Eligible for scholarship!

How && (AND) works:

  • For the if block to run, ALL conditions connected with && must be true
  • First check: age >= 18? YES (20 is >= 18)
  • Second check: hasLicense? YES (it's true)
  • Both are true, so the if block runs
  • If even ONE condition was false, the else block would run

Example 2: Using || (OR) - At Least One Condition Must Be True


public class OrOperator {
    public static void main(String[] args) {
        int marks = 45;
        boolean isExempt = false;
        
        if (marks >= 50 || isExempt) {
            System.out.println("You are approved!");
        } else {
            System.out.println("You need to score 50 or be exempt.");
        }
        
        // Another example
        String day = "Saturday";
        if (day.equals("Saturday") || day.equals("Sunday")) {
            System.out.println("It's weekend! Enjoy!");
        } else {
            System.out.println("It's a weekday. Go to work/school.");
        }
    }
}
Output:
You need to score 50 or be exempt.
It's weekend! Enjoy!

How || (OR) works:

  • For the if block to run, AT LEAST ONE condition connected with || must be true
  • First check: marks >= 50? NO (45 is not >= 50)
  • Second check: isExempt? NO (it's false)
  • Both are false, so the else block runs
  • If even ONE condition was true, the if block would run

Common Mistakes to Avoid

Mistake 1: Using = instead of ==


public class MistakeExample1 {
    public static void main(String[] args) {
        int x = 5;
        
        // WRONG: Using = (assignment) instead of == (comparison)
        // This will cause an error!
        // if (x = 5) { ... }
        
        // CORRECT: Use == to compare
        if (x == 5) {
            System.out.println("x equals 5");
        }
    }
}

Explanation: = assigns a value, while == compares two values. Always use == in conditions.

Mistake 2: Forgetting Curly Braces


public class MistakeExample2 {
    public static void main(String[] args) {
        int age = 20;
        
        // WRONG: Missing curly braces (only first line belongs to if)
        // if (age >= 18)
        //     System.out.println("You are an adult!");
        //     System.out.println("Welcome!"); // This runs always!
        
        // CORRECT: Use curly braces for multiple lines
        if (age >= 18) {
            System.out.println("You are an adult!");
            System.out.println("Welcome!");
        }
    }
}

Explanation: Always use {} even if you have only one line. It's safer and clearer.

Mistake 3: Using .equals() for numbers


public class MistakeExample3 {
    public static void main(String[] args) {
        int num = 10;
        
        // WRONG: .equals() is for Strings, not numbers
        // if (num.equals(10)) { ... }
        
        // CORRECT: Use == for numbers
        if (num == 10) {
            System.out.println("Number is 10");
        }
        
        // CORRECT: Use .equals() only for Strings
        String name = "Alice";
        if (name.equals("Alice")) {
            System.out.println("Hello Alice!");
        }
    }
}

Explanation: Use == for numbers and .equals() for text (Strings).

Summary of Common Mistakes:
1. Use == to compare, not =
2. Always use {} for if-else blocks
3. Use .equals() for Strings, == for numbers
4. Don't forget the else keyword

Real-World Example: Library Membership Check

Here's a practical program that uses if-else to check if someone can borrow a book:

Example: Library Borrowing System


public class LibrarySystem {
    public static void main(String[] args) {
        String memberName = "Alice";
        boolean isMember = true;
        int booksDue = 0;
        int maxBooks = 5;
        
        System.out.println("=== Library Borrowing System ===");
        System.out.println("Name: " + memberName);
        System.out.println();
        
        // Check if person is a member
        if (isMember) {
            System.out.println("✓ You are a registered member.");
            
            // Check if they can borrow more books
            if (booksDue < maxBooks) {
                System.out.println("✓ You can borrow books!");
                System.out.println("Books you can still borrow: " + (maxBooks - booksDue));
            } else {
                System.out.println("✗ You have reached the borrowing limit.");
                System.out.println("Please return some books first.");
            }
        } else {
            System.out.println("✗ You are not a member.");
            System.out.println("Please register first to borrow books.");
        }
    }
}
Output:
=== Library Borrowing System ===
Name: Alice

✓ You are a registered member.
✓ You can borrow books!
Books you can still borrow: 5

How this program works:

  • First if-else checks: Is this person a member?
  • If yes, it goes inside and checks another condition: Are they under the book limit?
  • Nested if-else: Shows welcome message if they can borrow, or warning if they can't
  • If not a member: Shows registration message
  • This combines variables, comparisons, and multiple if-else statements

Key Takeaways About if-else

One Block Always Runs

When you use if-else, exactly one block will run - never both, never neither. If the condition is true, the if block runs. If false, the else block runs.

Perfect for Opposite Choices

Use if-else when you have exactly two opposite options. Examples: yes/no, true/false, adult/child, pass/fail, hot/cold, member/non-member.

Conditions Can Be Complex

Your condition can check one thing (age >= 18) or multiple things combined (age >= 18 && hasLicense). Use && for "all must be true" and || for "at least one must be true".

You Can Nest if-else

You can put an if-else inside another if-else for more complex decisions. But don't nest too many levels or your code becomes hard to read.

Always Use Curly Braces

Use {} even for single lines. It makes your code clearer and prevents mistakes when you add more code later.