Understanding Java's Else Statement with Examples

Java Q&A Hub 使用 GPT-4o-mini 回答

问题:

Introduce Java Else and give examples

回答:

In Java, the else statement is used in conjunction with an if statement to provide an alternative block of code that executes when the condition in the if statement evaluates to false. This allows for conditional execution of code, enabling different paths of execution based on certain conditions.

Basic Syntax

The basic syntax of an if-else statement in Java is as follows:

if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}

Example 1: Simple If-Else

Here’s a simple example that checks if a number is positive or negative:

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

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

Output:

The number is negative.

Example 2: If-Else with Multiple Conditions

You can also use else if to check multiple conditions:

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

        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: D");
        }
    }
}

Output:

Grade: B

Example 3: Nested If-Else

You can also nest if-else statements within each other:

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

        if (age >= 18) {
            System.out.println("You are an adult.");
            if (age >= 65) {
                System.out.println("You are a senior citizen.");
            } else {
                System.out.println("You are not a senior citizen.");
            }
        } else {
            System.out.println("You are a minor.");
        }
    }
}

Output:

You are an adult.
You are not a senior citizen.

Summary

The else statement in Java is a powerful tool for controlling the flow of your program based on conditions. By using if, else if, and else, you can create complex decision-making structures that allow your program to respond differently based on varying inputs or states.