Course Content‎ > ‎Session 3‎ > ‎

Conditional Branching

Java language possesses the capabilities, which enable us to branch the execution of the program, depending on whether a certain condition is met or not. These statements are called as control or decision-making statements. Let's look at these statements and see how they work.

if Statement

if statement is used to control the flow of the execution of statements. It is a two-way decision statement. This allows the computer to evaluate the expression first, depending on whether the value of expression is true or false; control is transferred to a particular statement. if statement is implemented in different forms:

    if(test expression)
    {
        block of statements;
    }
    statement;

If block of statements consist of only one statement, it could also be written as:

    if(test expression) statement;

For example,

    // this statement will be executed if salary is less than 1000
    if(salary < 1000)
    {
    salary = salary + 1000;
    }
    /* This statement will be executed irrespective of whether the old 
       salary is less than or not less than 1000 */ 
    System.out.println("Salary is " + salary);

Or,

    /* the statement salary = salary + 1000; will be executed if salary 
       is less than 1000 */
    if(salary < 1000) salary = salary + 1000; 
     
    /* This statement will be exected irrespective of whether the old 
       salary is less than or not less than 1000 */
    System.out.println("Salary is " + salary);

It is always better to use curly braces i.e. { and }, even if there is only one statement, as it increases the readability and makes the code easier to understand.

if...else Statement

if...else statement is an extension of simple if statement. General form of if...else statement is:

    if(test expression is true)
    {
        block of statements(executed if test expression is true)
    }
    else
    {
        block of statements(executed if test expression is false)
    }          
    statement; 
    
If there is only one statement instead of block of statements if-else statement could also be written as:

    if(test expression) statement;
    else statement;

Or,

    if(test expression)
        statement;
    else
        statement; 

Let's look at  an example, illustrating the if statement

    int number;
    number = 23; 
    if((number % 2) == 0)
    {
        System.out.println("Number is even");
    }
    else
    {
        System.out.println("Number is odd");
    }
    
The above example could also be written as:

    if((number % 2)== 0)
        System.out.println("Number is even"); 
    else
        System.out.println("Number is odd");

Or ,

    if((number % 2)== 0) System.out.println("Number is even");
    else System.out.println("Number is odd");


if...else if...else statements

When multipath decisions are involved, it is a way of putting multiple ifs together. It takes the general form:

    if(conditon1)
    {
        statement block1;
    }
    else if(condition2)
    {
        statement block2;
    }
    else if(condition3)
    {
        statement block3;
    }
    else if(conditionn)
    {
        statement blockn;  
    }
    else
    {
        default statement block;
    }
    statement;
   
Given below is an example of if ..else..if hierarchy:

    if(salary >= 10000)
    { 
        // bonus will be 20% of the salary if salary is >= to 10000  
        bonus = salary * .2;
    }
    else if(salary >= 8000)
    {  
        /* bonus will be 30% of the salary if salary is >= to 8000 
           but < 10000 */
        bonus = salary * .3;
    }
    else if(salary >= 6000)
    {  
        /* bonus will be 50% of the salary if salary is >= to 6000 
           but < 8000  */
        bonus = salary * .5;
    }
    else
    {  
        // bonus will be 75% of the salary if salary is less than 6000 
        bonus = salary *.75;
    }  
    /* Irrespective of which path has been taken in if......else if...     
       else ladder, this statement will be printed. */
    System.out.println(" Bonus is : " + bonus); 


Nesting of if Statements

For example, to count the number of students, who have obtained percentage of marks greater than or equal to 90 and have obtained A grade in 4 or more subjects

    if (percentage >= 90)  
    {
        if(grade >= 4)  
        {  
            /* this statement is executed if percentage is greater than
               90 */
            count = count + 1;
        }
    }
    
The above code could also be written as :

    if(percentage >= 90 && grade >= 4)  
    {
        count=count+1;
    }   

Let’s take another example to illustrate nesting of if statements:

    if(height >= 175)
    {
        if(weight >110 && weight < 170)
        {  
            /* this statement is displayed if height is greater than or 
               equal to 175 cm and weight is greater than 110 and less
               than 170 */
            System.out.println ("Candidate is fit, can be considered for selection");
        }
        else  
        {  
            /* this statement is displayed if height is greater than or 
               equal to 175cm but weight is not greater than 110 and less 
               than 170 */
            System.out.println(" inappropriate weight, cannot be considered for selection");
        }
    }
    else
    {  
        /* this statement is displayed if neither height is greater than 
           or equal to 175cm nor weight is greater than 110 and less than 170 */
        System.out.println("candidate is not fit for selection");
    }
    
switch Statement

When only one of the many given alternatives has to be selected, we can design if statements in the program, to control the selection. However, complexity of the program increases, when number of alternatives increases. Program becomes difficult to read and follow. To solve this problem multi-way decision statement called as switch statement is used. switch statement tests the value of a given variable or expression against a list of case values and when a match is found, a block of statements associated with that case is executed.

NOTE: case statements cannot evaluate Strings or objects

General form of switch statement is:  

    /* test is a variable or expression that evaluates to any data type */  
    switch(test)
    {
        case value1:
            block of statements;
            break;
        case value2 :  
            block of statements;
            break;  
        case value3 :
            block of statements;
            break;
        ...
        default :
            default block;
            break;
    }
    statements;
    
value1, value2 are constants or constant expressions. They are called as case labels. test is compared with each of the case values i.e. first it is compared to value1, if match is found the corresponding block of statements get executed; otherwise test is compared to value2, if match is found the corresponding block of statements get executed; otherwise test is compared to value3 and so on. If no match is found for test, then the default block gets executed.

Given below is an example using switch statement:

    class add
    {
        public static void main(String args[]) throws Exception
        {
            int num1, num2, result;
            char choice;
            result=0;
            num1=20;
            num2=12;  

            System.out.println("Press A or a for Addition");
            System.out.println("Press S or s for Subtraction");
            System.out.println("Press M or m for  Multiplication");
            System.out.println("Press D or d for  Division");
            System.out.println("Please select your choice by entering a character A, S, M, D");  

            /* to accept the choice from the user, as System.in.read( )
               returns an int value, so it has been typecasted to char */
            choice = (char)System.in.read( );

            switch(choice)
            {  
                /* if choice is A or a, the operation to be performed is 
                   addition */
                case 'A':   
                case 'a' :
                    result = num1 + num2;
                    System.out.println("Sum of two numbers is " + result);
                    break;  
                /* if choice is S or s, the operation to be performed is 
                   subtraction */ 
                case 'S': 
                case 's':
                    result = num1 - num2; 
                    System.out.println("Result of subtraction of two numbers is " + result);
                    break;
                /* if choice is M or m, the operation to be performed is 
                   multiplication */ 
                case 'M':    
                case 'm':
                    result = num1 * num2;
                    System.out.println("Multiplication of two numbers is " + result);
                    break;
                /* if choice is D or d, the operation to be performed is 
                   division */ 
                case 'D':    
                case 'd':
                    result = num1 / num2;
                    System.out.println("Division of two numbers is" + result);
                    break;
                default:
                    System.out.println(" you have entered an invalid choice, please press 'A','S','M' or 'D' ");
                    break;
            }
        }
    }


Comments