🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Nested if Statements

Java Nested If Statement Example

In Java, you can use nested if statements to create a structure where one if statement is placed inside another. This allows you to check multiple conditions in a hierarchical manner. Each inner if statement is executed based on the result of its outer if statement.

Example:

public class NestedIfStatementExample {
    public static void main(String[] args) {
        int x = 10;
        int y = 5;

        if (x > 0) {
            System.out.println("x is positive");

            if (y > 0) {
                System.out.println("y is positive");
            } else {
                System.out.println("y is non-positive");
            }

        } else {
            System.out.println("x is non-positive");
        }
    }
}

In this example:

  • The outer if statement checks if x is positive.
  • If x is positive, the inner if statement checks if y is positive.
  • Depending on the conditions, different messages are printed.

It's important to properly indent the code to maintain clarity. Nested if statements can be used to handle more complex decision-making scenarios. However, it's essential to be mindful of code readability to avoid confusion.

if (condition1) {
    if (condition2) {
        // Code for condition1 and condition2
    } else {
        // Code for condition1 and not condition2
    }
} else {
    // Code for not condition1
}

Keep in mind that excessive nesting can lead to code that is hard to read and maintain. In some cases, refactoring the code using logical operators (&&, ||) or introducing separate methods may improve readability.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.