Home » Java if-else Statement: A Comprehensive Tutorial with Code Examples

Java if-else Statement: A Comprehensive Tutorial with Code Examples

The if-else statement is one of the most basic and widely used control flow structures in Java. It allows the execution of different blocks of code based on whether a condition evaluates to true or false.

This tutorial will walk you through the various forms of the if-else statement, showing examples of how to use it in different scenarios.

Table of Contents:

1. What Is an if-else Statement?

An if-else statement is a control flow statement that allows you to conditionally execute a block of code based on whether a boolean expression evaluates to true or false.

General Syntax:

if (condition) {
    // Executes if the condition is true
} else {
    // Executes if the condition is false
}

condition: A boolean expression that is evaluated.
If true: The code inside the if block is executed.
If false: The code inside the else block (if present) is executed.

2. Basic if Statement

The simplest form of an if statement checks a condition and executes a block of code if the condition evaluates to true.

Example 1: Basic if Statement

public class Main {
    public static void main(String[] args) {
        int number = 10;

        // Check if the number is positive
        if (number > 0) {
            System.out.println("The number is positive.");
        }

        System.out.println("This statement always executes.");
    }
}

Output:

The number is positive.
This statement always executes.

Here, the condition number > 0 is true, so the if block is executed.

3. if-else Statement

An if-else statement is used when you need to execute one block of code if the condition is true and another block if the condition is false.

Example 2: if-else Statement

public class Main {
    public static void main(String[] args) {
        int number = -5;

        // Check if the number is positive or negative
        if (number > 0) {
            System.out.println("The number is positive.");
        } else {
            System.out.println("The number is negative.");
        }
    }
}

Output:

The number is negative.

In this case, the condition number > 0 is false, so the else block is executed.

4. else if Ladder

When you have multiple conditions to check, you can use the else if ladder. This structure allows you to chain multiple conditions together.

Example 3: else if Ladder

public class Main {
    public static void main(String[] args) {
        int score = 85;

        // Check multiple conditions using else if
        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else if (score >= 70) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: F");
        }
    }
}

Output:

Grade: B

Here, the else if ladder checks multiple conditions in sequence. Once a condition is true, the corresponding block is executed, and the rest of the conditions are skipped.

5. Nested if-else Statements

You can nest if-else statements inside other if-else statements to handle complex conditions.

Example 4: Nested if-else

public class Main {
    public static void main(String[] args) {
        int number = 15;

        // Nested if-else example
        if (number > 0) {
            if (number % 2 == 0) {
                System.out.println("The number is positive and even.");
            } else {
                System.out.println("The number is positive and odd.");
            }
        } else {
            System.out.println("The number is negative.");
        }
    }
}

Output:

The number is positive and odd.

In this example, the first if checks if the number is positive, and the second (nested) if-else checks if the number is even or odd.

6. Ternary Operator (?:)

The ternary operator is a shorthand version of the if-else statement. It’s useful for simple conditional logic and assigning values based on a condition.

Syntax:

condition ? value_if_true : value_if_false;

Example 5: Ternary Operator

public class Main {
    public static void main(String[] args) {
        int number = 10;

        // Ternary operator for checking positivity
        String result = (number > 0) ? "Positive" : "Negative";
        System.out.println("The number is " + result);
    }
}

Output:

The number is Positive

The ternary operator allows you to evaluate number > 0 and assign either “Positive” or “Negative” to result.

7. Best Practices for if-else Statements

Avoid deep nesting: Deeply nested if-else blocks can make your code harder to read. Consider using methods to break complex logic into simpler parts.
Use else if instead of multiple if: When checking mutually exclusive conditions, prefer else if to avoid unnecessary evaluations.

Example 6: Avoid Unnecessary if

// Inefficient way:
if (x == 1) { ... }
if (x == 2) { ... }

// More efficient:
if (x == 1) { ... }
else if (x == 2) { ... }

Use the ternary operator for simple conditions: When you need to conditionally assign a value, the ternary operator can simplify your code.
Always handle all possible conditions: Always provide an else or else if block to handle cases where none of the conditions match.

8. Common Use Cases for if-else

Example 7: Checking User Input

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a number:");
        int number = scanner.nextInt();

        if (number > 0) {
            System.out.println("The number is positive.");
        } else if (number < 0) {
            System.out.println("The number is negative.");
        } else {
            System.out.println("The number is zero.");
        }
    }
}

Output (Example input: 0):

The number is zero.

This example checks whether the user input is positive, negative, or zero.

Example 8: Age-Based Conditions

public class Main {
    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.

Here, the if condition checks if the person is legally an adult based on their age.

Conclusion

The if-else statement is one of the most fundamental control structures in Java, allowing you to execute code conditionally.

By understanding how to use if, if-else, else if, and the ternary operator, you can write clear and efficient conditional logic.

Whether you are performing basic checks, validating user input, or dealing with complex logic, the if-else statement provides the flexibility to handle various conditions in your programs.

You may also like