Nested if and Multi-Way if-else Statements

Nested if and Multi-Way if-else Statements:

        An if statement can be nested inside another if statement, forming a nested if statement. This allows for more complex decision-making in a program.

        In a nested if statement, an if statement is placed inside another if statement. The inner if statement is considered to be nested within the outer if statement. There is no limit to the depth of nesting and an inner if statement can also contain another if statement.

        Here is an example of a nested if statement:

    1. if (i > k) {
    2.     if (j > k)
    3.         System.out.println("i and j are greater than k");
    4. }
    5. else {
    6.     System.out.println("i is less than or equal to k");
    7. }

        In this example, the inner if statement `if (j > k)` is nested inside the outer if statement `if (i > k)`. This allows for different actions to be taken based on multiple conditions.

        A nested if statement can be used to implement multiple alternatives. Figure-1a shows an example of an if statement with multiple conditions to determine a letter grade based on a score.

Figure-1


        The execution of a nested if statement proceeds by testing each condition in order. If a condition evaluates to true, the corresponding action is taken, and the rest of the conditions are skipped. If all of the conditions evaluate to false, the final else block is executed.

        It is important to note that a condition is tested only when all the preceding conditions are false. This ensures that only one action is performed based on the first condition that evaluates to true, and the subsequent conditions are not checked. 

        The execution of this if statement proceeds as shown in Figure-2. The first condition (score >= 90.0) is tested. If it is true, the grade is A. If it is false, the second condition (score >= 80.0) is tested. If the second condition is true, the grade is B. If that condition is false, the third condition and the rest of the conditions (if necessary) are tested until a condition is met or all of the conditions prove to be false. If all of the conditions are false, the grade is F. Note that a condition is tested only when all of the conditions that come before it are false.

Figure-2

        The if statement in Figure-1 a is equivalent to the if statement in Figure-1 b. In fact, Figure 3.3b is the preferred coding style for multiple alternatives if statements. This style, called multi-way if-else statements, avoids deep indentation and makes the program easy to read.




Comments

Popular posts from this blog

Types of Operators (Augmented assignment, Increment and Decrement, Logical)

History of The Java

Creating, compiling and Executing a simple java program