Java If-Else-If Ladder and Nested If Statements

Control Flow and Decision Making in Java

Before start discussing Java's control flow statements it would be nice to know that Java is a structured programming language and Java program statements can be executed sequentially, conditionally (with the help of if-else, and switch), iteratively (with the help of loops) or by following a combination of all depending upon the program logic. Conditional and iterative execution of program statements is done by control flow statements. Conditional statements in Java include if, else, switch and case statements, while iterative statements include for, while, and for statements.

Decision Making in Java

To facilitate conditional control flow in Java there are relational and logical operators to form a conditional expression that returns either true or false. Words true and false look like keywords but they are boolean literals actually and cannot be used as identifiers in Java programs. Java program decides the execution path on basis of the truth or falsehood of conditional expression.

Java Statements and Blocks

In a Java program zero or more statements enclosed in a pair of curly braces make a block of statements. A block is treated as a single unit and can be used where a single statement is allowed. In fact, a block is a statement but this is a compound statement. We will soon come to know the worth of a block when we will have to control more than one statement by decision making constructs of Java.

Java If Statement

An if statement is the most basic Java control flow statement you will see in Java programs along with an optional else part. Following is the general syntax of if statement:

if (booleanExpression) 
   statement-1;

OR

if (booleanExpression) 
{
    statement-1;
    statement-2;
    .
    .
    .
    statement-n;
}

The booleanExpression in parentheses must return a boolean true or false or Boolean (boolean wrapper). The expression can be a relational or logical expression or a function call that returns a boolean literal. Above syntax will execute statement-1 to statement-n if the booleanExpression in parentheses returns true, nothing otherwise.

By default if controls only one statement, therefore if you wish to control only one statement by if, you need not to enclose the only statement within curly braces. But, it is good to use braces every time with if because it increases readability of the program. If there are two or more statements to be controlled by if conditional, they all must be enclosed in curly braces. A set of statements enclosed in braces is called a block or a compound statement. For demonstration, consider the following example program:

//Demonstrates if-else statements
public class ControlFlowDemo
{
    public static void main(String[] args)
    {
        int x = 10, y = 20;
        boolean decision = false;
 
        //if controls one statement by default, so no braces required
        if(x < y) 
            System.out.println(x + " is less than " + y + "\n");
 
        if (decision)
            System.out.println("always false\n"); //will never be printed
 
        if (isPositive(x))
            System.out.println(x + " is positive: " + isPositive(x) + "\n");
 
        if (x > y)
        {
            System.out.println("Within from if block");
            System.out.println(x + " greater than " + y + "\n");
        }
        else
        {
            System.out.println("Within from else block");
            System.out.println("Optional else used when there are two branches");
            System.out.println(x + " less than " + y + "\n");
        }
 
        //will print "yes, variable decision is false"
        if (decision == false) 
            System.out.println("Yes, variable decision is false\n"); 
 
        //what do you think it will print?
        if (decision = true) 
            System.out.println("Variable decision is assigned to true"); 
    }
 
    // number is positive if it is greater than zero
    public static boolean isPositive (int n1)
    {
        return (n1 > -1);
    }
}
 
OUTPUT
======
10 is less than 20
 
10 is positive: true
 
Within from else block
Optional else used when there are two branches
10 less than 20
 
Yes, variable decision is false
 
Variable decision is assigned to true
 

In above example code, look at the second if statement if (decision), where variable decision returns false, therefore the statement System.out.println("always false\n"); will not be executed and nothing will be printed.

Next, in if (decision == false) statement, variable decision is being checked for equality against boolean literal false. As variable decision contains false so it will pass the equality test and will return true.

Finally, in the last most if statement decision = true is not a valid relational or logical expression, while it is a mere assignment operation and boolean literal true is being assigned to variable decision. But, still there is no error and code is executed successfully because this is eventually evaluated to true.

Java Nested If Statement

When an if statement appears inside the other it is called nesting of if statements. Nesting of if statements is very helpful when you have something to do by following more than one decision. For example, if you meet your daughter's school teacher every second Saturday of the month to get to know the performance of your doll then your meeting is followed by two decisions. First, it should be a Saturday then it should be the second of the month. And more practically, the third one is that it should not be a holiday. Let's program your meeting schedule as follows:

boolean isSat = true;
int whichSat = 2;
boolean isHoliday = false;
 
if (isSat)
{
    if (whichSat == 2)
    {
        if (isHoliday == false)
        {
            System.out.println("It is meeting today.");
        }
    }
}
else
{
    System.out.println("No meeting today.");
}

While nesting if statements we must know that an else statement is always bound to its closest if. Following piece of code demonstrates that:

int i = 10, j = 15, k = 50, a = 5, b = 7, c = 9, d = 11;
 
if(i == 10) 
{
    if(j < 20) a = b;
        if(k > 100) c = d; 
    else a = c; // associated with if(k > 100)
}
else a = d; // associated with if(i == 10)
System.out.println(a);
 
OUTPUT
======
9

Java If-Else Ladder

Java control flow statements are executed from top to down, therefore, a ladder of if-else conditions will be evaluated from top to down. As soon as an if statement from the ladder evaluates to true, the statements associated with that if are executed, and the remaining part of the ladder is bypassed. The last most else is executed only when no condition in the whole ladder returns true.

Here is a program which demonstrates if-else ladder. It determines if a given alphabet is vowel or consonant.

//Demonstrates if-else ladder
public class ControlFlowDemo
{
    public static void main(String[] args)
    {
        char ch = 'o';
 
        if (ch == 'a' || ch == 'A')
            System.out.println(ch + " is vowel.");
        else if (ch == 'e' || ch == 'E')
            System.out.println(ch + " is vowel.");
        else if (ch == 'i' || ch == 'I')
            System.out.println(ch + " is vowel.");
        else if (ch == 'o' || ch == 'O')
            System.out.println(ch + " is vowel.");
        else if (ch == 'u' || ch == 'U')
            System.out.println(ch + " is vowel.");
        else
            System.out.println(ch + " is a consonant.");
	}
}
 
OUTPUT
======
o is vowel.

In above program, one and only one println statement will be executed, no matter what is the value of ch from a-z or A-Z.

Last Word

In this tutorial we explained how decisions are made by using relational and logical operators in Java and Java's if-else, nested if, and if-else-if ladder statements. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

References



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.