Nested if statement in Java

In Java, we can use nested if statements to create more complex conditional logic. Nested if statements are if statements inside other if statements.

Syntax:

if (condition1) {
    // code block 1
    if (condition2) {
        // code block 2
    }
}

Below is the implementation of Nested if statements:

Java
// Java Program to implementation
// of Nested if statements

// Driver Class
public class AgeWeightExample {
      // main function
    public static void main(String[] args) {
        int age = 25;
        double weight = 65.5;
      
        if (age >= 18) {
            if (weight >= 50.0) {
                System.out.println("You are eligible to donate blood.");
            } else {
                System.out.println("You must weigh at least 50 kilograms to donate blood.");
            }
        } else {
            System.out.println("You must be at least 18 years old to donate blood.");
        }
    }
}

Output
You are eligible to donate blood.

Note: The first print statement is in a block of “if” so the second statement is not in the block of “if”. The third print statement is in else but that else doesn’t have any corresponding “if”. That means an “else” statement cannot exist without an “if” statement.

Java if-else

Decision-making in Java helps to write decision-driven statements and execute a particular set of code based on certain conditions. The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. In this article, we will learn about Java if-else.

Similar Reads

If-Else in Java

If- else together represents the set of Conditional statements in Java that are executed according to the condition which is true....

Syntax of if-else Statement

if (condition) { // Executes this block if // condition is true } else { // Executes this block if // condition is false }...

Java if-else Flowchart

...

if-else Program in Java

Dry-Run of if-else statements...

Nested if statement in Java

In Java, we can use nested if statements to create more complex conditional logic. Nested if statements are if statements inside other if statements....

Frequently Asked Questions

What is the if-else in Java?...