Java Conditional Statements if-else: Master Branch Logic Easily with Examples

Mastering Java Conditional Statements: The Basics of if-else for Branching Logic

I. Why Conditional Statements?

In daily life, we often make choices based on different scenarios: e.g., “If it rains, take an umbrella; otherwise, don’t” or “If the score is ≥60, pass; otherwise, fail”. In Java, conditional statements (such as if-else) implement this logic: “First judge a condition, then decide which code to execute”. Without conditionals, programs can only run code sequentially, failing to handle complex scenarios.

II. if Statement: Single-Branch Conditional Judgment

Syntax:

if (condition) {
    // Code executed when condition is true
}
  • Condition: Must return a boolean (true or false), e.g., num > 0, score >= 60.
  • Code Block: Executes the code inside the braces if the condition is true; otherwise, skips it.

Example 1: Check if a number is positive

public class IfExample {
    public static void main(String[] args) {
        int num = 5; // Define an integer
        if (num > 0) { // Judge if num is positive
            System.out.println("This is a positive number"); // Executed if condition is true
        }
        // If num is 0 or negative, the code in braces is not executed
    }
}

Output: This is a positive number

III. if-else Statement: Two-Branch Conditional Judgment

Use if-else when two outcomes are needed (e.g., “positive” or “non-positive”).

Syntax:

if (condition) {
    // Executed when condition is true
} else {
    // Executed when condition is false
}

Example 2: Check if a number is positive or non-positive

public class IfElseExample {
    public static void main(String[] args) {
        int num = -3;
        if (num > 0) {
            System.out.println("This is a positive number");
        } else {
            System.out.println("This is not a positive number (could be 0 or negative)");
        }
    }
}

Output: This is not a positive number (could be 0 or negative)

IV. if-else if-else Statement: Multi-Branch Conditional Judgment

Use if-else if-else to handle multiple conditions (e.g., “score levels”).

Syntax:

if (condition1) {
    // Executed if condition1 is true
} else if (condition2) {
    // Executed if condition1 is false and condition2 is true
} else if (condition3) {
    // Executed if conditions 1 and 2 are false, and condition3 is true
} else {
    // Executed if all conditions are false
}

Example 3: Determine score level

public class IfElseIfExample {
    public static void main(String[] args) {
        int score = 85;
        if (score >= 90) {
            System.out.println("Excellent");
        } else if (score >= 80) {
            System.out.println("Good");
        } else if (score >= 60) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }
    }
}

Output: Good

V. Notes and Common Mistakes

  1. Condition Expression Symbols
    - Error: Use assignment = instead of comparison == (e.g., if (num = 5) causes a compile error).
    - Correct: if (num == 5) (where == is the comparison operator).

  2. Condition Order in Multi-Branch
    - Example of error (wrong order):

     // Wrong: Smaller range condition is checked first
     if (score >= 60) { // Fails to distinguish "90+" as "Excellent"
         System.out.println("Pass");
     } else if (score >= 90) {
         System.out.println("Excellent");
     }
  • Correct Order: Check broader ranges first, then narrower ones (or vice versa based on logic).
  1. Braces Usage
    - Error: Omit braces for single-line code (risky for future modifications).
     if (num > 0)
         System.out.println("Positive"); // Risky if modified later
  • Recommendation: Always use braces to wrap code blocks for clarity and avoid bugs.

VI. Nested if-else (Advanced)

Nesting if or else inside another if enables complex logic.

Example 4: Check if a number is a positive even number

public class NestedIfExample {
    public static void main(String[] args) {
        int num = 4;
        if (num > 0) { // Outer condition: positive number
            if (num % 2 == 0) { // Inner condition: even number
                System.out.println("This is a positive even number");
            } else {
                System.out.println("This is a positive odd number");
            }
        } else {
            System.out.println("This is not a positive number");
        }
    }
}

Output: This is a positive even number

VII. Summary

  • Core Role: Choose code blocks to execute based on conditions, enabling branching logic.
  • Basic Structures: if (single branch), if-else (two branches), if-else if-else (multiple branches).
  • Key Details:
  • Use == for comparison, not = (assignment).
  • Order conditions logically to avoid overlapping.
  • Always use braces to define code blocks for clarity.

With the above examples and notes, beginners can quickly master if-else basics. For more complex scenarios, nested conditionals can be combined.

Xiaoye