Understanding Java If...Else Statements with Examples

Answered using GPT-4o-mini by Java Q&A Hub

Question:

Introduce Java If ... Else and give examples

Answer:

In Java, the if...else statement is a fundamental control flow statement that allows you to execute certain blocks of code based on whether a specified condition evaluates to true or false. This is useful for making decisions in your code.

Syntax

The basic syntax of the if...else statement is as follows:

if (condition) {
    // Code to be executed if the condition is true
} else {
    // Code to be executed if the condition is false
}

You can also have multiple else if statements to check additional conditions:

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if both conditions are false
}

Examples

Example 1: Basic If...Else

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

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

Output:

The number is positive.

Example 2: If...Else with 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

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 not an adult.");
        }
    }
}

Output:

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

Summary

The if...else statement is a powerful tool in Java that allows you to control the flow of your program based on conditions. By using if, else if, and else, you can create complex decision-making structures in your code.