Java if, if-else,if-else if-else statements

Java if

Java if is used as a condition statement whereby a statement or block of code statement(s) are executed  if the condition under evaluation returns true.

Syntax:

If(booleanExpression){

//statement(s) to execute when booleanExpression evaluates to true

}

The booleanExpression could be a boolean/Boolean variable,an equality check statement e.g. ‘x>y’,’4<7’,str=”abc”,or even a method that returns a boolean e.g. method with signature public boolean valid(int input) whereby the input int is validated and a true or false returned if it is valid or not.

Example 1

package devsought.ifelse;

 

public class JavaIfExample1 {

 

    public static void main(String... args) {

        if (2 < 5) {

            System.out.println("2 is less than 5");

        }

        System.out.println("More statements");

    }

}

On running the above program we get below output:

2 is less than 5

More statements

Explanation: The condition 2<5 evaluates to true therefore we enter the block under the if statement and execute the statements therein hence the line "2 is less than 5" is printed. The line "More statements" is printed regardless of the result of the condition evaluation as it not under evaluation.

If we change the condition expression to say if(5<2) we get output as below:

More statements

Only “More statements” is printed as the if evaluation returns false and the statements in the if block are not executed.

Java if-else

This is an if statement with an else block which has statement(s) to be executed in the instance that the boolean expression under evaluation returns false.

Syntax:

If(booleanExpression){

//statement(s) to execute when booleanExpression evaluates to true

}else{

//statement(s) to execute when booleanExpression evaluates to false

}

Example 2

package devsought.ifelse;

 

public class JavaIfExample2 {

 

    public static void main(String... args) {

        int a = 4;

        int b = 6;

        if (a < b) {

            System.out.println(a + " is less than " + b);

        } else {

            System.out.println(a + " is greater than " + b);

        }

 

    }

}

On running the above program the output is as follows:

4 is less than 6

If we change the value of a to 8 and rerun, the output now changes to as follows

8 is greater than 6

Explanation:

When a=4 and b=6,the boolean evaluation 4<6 returns true and we enter the statement block under the if condition hence the output ‘4 is less than 6’.

When we change to a=8,the if evaluation evaluates to false and we enter the else block hence the output ‘8 is greater than 6’

Java if-else if

This is a conditional construct whereby more than one condition needs to be evaluated. The else if statements can be one to many. If any of the else-if blocks evaluates to true, none of the remaining else if blocks are evaluated regardless of whether any of them will evaluate to true.

Syntax

If(booleanExpression1){

//statement(s) to execute when booleanExpression1 evaluates to true

}else if(booleanExpression2){

//statement(s) to execute when booleanExpression1 evaluates to false and booleanExpression2 evaluates to true

}

.

.

.

.

.

else if(booleanExpressionN){

//statement(s) to execute when none of all preceding else if blocks evaluate to true.

}

Example 3

package devsought.ifelse;

public class JavaIfExample3 {

 

    public static void main(String... args) {

        int a = 19;

        int b = 4;

        int mid = 50;

        int upper = 80;

        int lower = 15;

        if (a < b) {

            System.out.println(a + " is less than " + b);

        } else if (a < lower) {

            System.out.println(a + " is less than " + lower);

        } else if (a < mid) {

            System.out.println(a + " is less than " + mid);

        } else if (a < upper) {

            System.out.println(a + " is less than " + upper);

        }

 

    }

}

Once we run the above program ,output is as below:

19 is less than 50

Explanation:

The evaluation 19<4 returns false,so we go to the first else if block where we check 19<15 which also evaluates to false .We proceed to the next check 19<50 which evaluates to true and we enter that block of statements and output “19 is less than 50”.No further else-if’s are evaluated even though there could be more conditions which could evaluate to true downstream e.g. 19<80.

Java if…else if…else

This is a conditional construct to execute more than two alternatives based on more than two boolean condition evaluations. In this scenario there is one if statement, one to many else-if statements and one else block which will be executed when all preceding else if statements fail. In the case of multiple else-if statements, if one else-if condition evaluates to true, the remaining else-if statements and the final else  are not evaluated regardless whether any of them will evaluate to true.

 

Syntax:

If(booleanExpression1){

//statement(s) to execute when booleanExpression1 evaluates to true

}else if(booleanExpression2){

//statement(s) to execute when booleanExpression1 evaluates to false and booleanExpression2 evaluates to true

}

.

.

.

.

.

.

}else if(booleanExpressionN){

//statement(s) to execute when all preceding booleanExpressions evaluate to false and booleanExpressionN evaluates to true

}else{

//statement(s) to execute when all preceding if and else if statements upto booleanExpression N evaluate to false

}

Example 4

package devsought.ifelse;

 

public class JavaIfExample4 {

 

    public static void main(String... args) {

        int a = 82;

        int b = 4;

        int mid = 50;

        int upper = 80;

        int lower = 15;

        if (a < b) {

            System.out.println(a + " is less than " + b);

        } else if (a < lower) {

            System.out.println(a + " is less than " + lower);

        } else if (a < mid) {

            System.out.println(a + " is less than " + mid);

        } else if (a < upper) {

            System.out.println(a + " is less than " + upper);

        } else {

            System.out.println(a + " is greater than " + b);

        }

 

    }

}

When we run the above program we get output as below.

82 is greater than 4

Explanation:

The condition 82<4 evaluates to false so we proceed to the first else if where we test 82<15 which evaluates to false,we then proceed to 82<50 and 82<80 which all return false.We then end up in the final block,the else block after all preceding evaluations have failed/returned false.At this stage,we get the output ‘82 is greater than 4’.

Nested if-else statements-not a good practice

If-else statements can also be nested. Though this is not a good practice as it increases code readability challenge ,it gives us an opportunity to evaluate more scenarios/conditions.

Example

If(booleanExpression1){

//statement(s) to execute when booleanExpression1 evaluates to true

 

}else if(booleanExpression2){

//we enter this section if booleanExpression1 above evaluates to false and expression2 evaluates to true

//nested if-else

If(booleanExpression3){

//in this section both booleanExpression2 and booleanExpression3 evaluate to true

}else{

//in this section booleanExpression3 evaluate to false

}

}else if(booleanExpression4){

//we enter this section if booleanExpression2 above evaluates to false and expression4 evaluates to true

}else{

//in this section all preceding if  and else-if blocks have all evaluated to false.

}

Example 5

package devsought.ifelse;

 

public class JavaIfExample5 {

 

    public static void main(String... args) {

        int a = 22;

        int b = 24;

        int mid = 50;

        int upper = 80;

        int lower = 15;

        if (a < b) {

            if (a < lower) {

                System.out.println(a + " is less than " + b + " and less than" + lower);

            } else {

                System.out.println(a + " is less than " + b + " and greater than" + lower);

            }

        } else if (a < mid) {

            System.out.println(a + " is less than " + mid);

        } else if (a < upper) {

            System.out.println(a + " is less than " + upper);

        } else {

            System.out.println(a + " is greater than " + b);

        }

 

    }

}

When we run the above program,we get output as below.

22 is less than 24 and greater than15

Explanation:

The evaluation 22<24 returns true and we enter the block in the if statement.Inside that block we further evaluate 22<15 which returns false hence we enter the else block where we hence the line

‘22 is less than 24 and greater than15’ is printed.

If statement-one liner & statements executed

In this construct we have an if statement without enclosing curly braces. If it evaluates to true,the statement below it is executed,if not the statement is not executed .

Syntax:

If(booleanExpression)

Statement1;

Statement2;

Statement3;

If booleanExpression evaluates to true,Statement1,Statement2 and Statement3 are executed,otherwise if it evaluates to false,only Statement2 and Statement3 are executed.

Example -nested one liner ifs

if(booleanExpression1)

if(booleanExpression2)

Statement1;

else

Statement2;

else

Statement3;

If booleanExpression1 evaluates to true and booleanExpression2 to false ,only statement2 is executed as a result of booleanExpression2 being false.If booleanExpression1 evaluates to false,only Statement3 is executed.

 

Sample program:

package devsought.ifelse;

 

public class NestedOneLinerIf {

 

    public static void main(String... args) {

        if (3<5)

        if (4>10)

        System.out.println("Statement1");

        else

        System.out.println("Statement2");           

         else

        System.out.println("Statement3");   

 

    }

}

Output of the above program is ‘Statement2’.

Explanation:The first if evaluation 3<5 returns true,we enter the block which leads us to further evaluate 4>10 which returns false hence the statement is ‘Statement2’ is printed.

If we change the first if to 6<5 ,the output now becomes ‘Statement3’.This is because the evaluation 6<5 returns false hence we jump to the else block ,the final else block in our above program.

NB:In one liner nested if-else statement,the innermost else belongs to the innermost if.

The above program would have been rewritten clearly with curly braces as below.

package devsought.ifelse;

 

public class NestedOneLinerRefactored {

 

    public static void main(String... args) {

        if (3 < 5) {

            if (4 > 10) {

                System.out.println("Statement1");

            } else {

                System.out.println("Statement2");

            }

        } else {

            System.out.println("Statement3");

        }

 

    }

}

Example 6

package devsought.ifelse;

 

public class JavaIfExample6 {

 

    public static void main(String... args) {

        int a = 22;

        int b = 24;

        int mid = 50;

        int upper = 80;

        int lower = 15;

        if (a < b)

        System.out.println(a + " is less than " + b);

        System.out.println("b= "+b);

        System.out.println("lower= "+lower);

        System.out.println("mid= "+mid);

        System.out.println("upper= "+upper);

 

    }

}

When we run the above program, we get the below output.

22 is less than 24

b= 24

lower= 15

mid= 50

upper= 80

Explanation: The check 22<24 evaluates to true therefore the first line to be printed is ‘22 is less than 24’.The other lines are not affected by the condition and are printed.

When we change the value of a to say 25,the first line to be printed is ‘b= 24’.The output in such a case is as below.

b= 24

lower= 15

mid= 50

upper= 80

Recap-Tips

  1. For a given if we can have zero or one else statement and the else statement will come after else if statements if any.
  2. For a given if statement we can have zero to many else-if statements and these come before any else
  3. In case an else-if statement succeeds, none of the remaining else-if or else statements will be executed.

Tip:assignment and testing

Boolean valid=true;

If(valid=false){

Statement1;

}else{

Statement2:

}

In the above ,Statement2 is executed since valid was reset to false and the if check evaluated to false.

Example 7

package devsought.ifelse;

 

public class JavaIfExample7 {

 

    public static void main(String... args) {

        boolean valid = false;

        if (valid=true) {

            System.out.println("Valid");

        } else {

            System.out.println("Invalid");

        }

 

    }

}

Once we run the above program,we get output ‘Valid’ .

In the if condition evaluation,we assigned true to variable valid instead of evaluating it.The result of the assignment was true which made the subsequent evaluation to be true hence the statement ‘Valid’ was printed.

The programs used in this tutorial are avaiable on Github.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.