Decision Making Statements (if() , if_else() , Multiple if() , Nested if() and switch case statement ) (Java)

Decision is very important aspect of life. Almost everything depends upon the decision. You also take decision in your life. For Example: A Job is to be done or not also depends upon the decision. Same way a Java program is a set of statements, which are normally executed sequentially (i.e., statement-by-statement from top to bottom in a Java method) in the same order as they appear. While programming/coding we came across certain situations, where we may have to change the order of execution of statements based on certain conditions, or repeat a group of statements for known number of times. In such cases, the order in which these statements will execute is to be controlled.

Program Construct:

They are devided into following categories:

1) Sequence : The sequence construct means statements executes in sequence.
2) Selection - if(), switch() : The selection construct means the statements executes depending upon the used conditions.
3) Iteration - while(), do_while(), for() : The iteration construct means repetition of set of statements upto a limit depending upon condition.

Let us understand the Selection Statements.

Selection Construct:

Lets start this Selection Statements with some examples by which you will get an idea about it. There are some situation in which we need to take some decisions in our life.
Such as,
  1. If room is dark then switch ON the light.
  2. If you are hungry then you will eat.
  3. If you go to school then you will be educated.
  4. If you don't study then you will fail.
As you can see in the above examples that, an action will be true or done if the specified condition is true.

Selection statements are also known as branching statements and decision statements and conditional statements. 

The Selection Statements are mainly divided into two parts :

(1) if(), and
(2) switch().

Let us study different if() statements in detail:

1.1 if( )

Definition: This statement is used to check one or more than one condition(s).

Syntax: 
            if(condition or relational expression)
            {
                set of statements/expressions;
            }

When the condition is true the control will execute the statements given within the curly braces '{ }'.

Note: If the selection statement if() contain only one statement then the curly braces '{ }' may be omitted (leave out).

Example:
      class sample_if
    {
        public void main()
        {
            int a = 15,b = 10;
            if(a > b)
            {
                System.out.println(a + " is big");
            }
        }
    }

The output of the above program is 15 is big, since the value of a = 15, is bigger than 'b = 10' , hence the statement within if( ) blocks executes and print value of variable 'a' with message "is big". i.e., 15 is big.

1.2 if-else( )

Definition: This decision making statement is used to execute the statements given within if( ) block when the condition results true otherwise the statements given within else block gets executed.
In simple words this conditional statement works both for true and false decisions.

Syntax:
            if(condition or relational expression)
           {
               set of statements/expressions;
           }
           else
           {
               set of statements/expressions;
           }

How it works?
The statements/expressions given within the curly braces of the if( ) statement will execute when the condition is true otherwise when the condition is false then the statements/expressions within the else curly braces gets executed.

Example:
        class sample_if_else
        {
            public void main()
            {
                int a = 5;
                int b = 10; 
                {
                    System.out.println(a + " is big");
                }
                else
                {
                    System.out.println(b + " is big");
                }
            }
        }

The above program will produce the output as 10 is big, since the value 'a'which is 5 and smaller than 'b' which is 10 hence the statement within else executes and prints value of variable 'b' followed by message "is big" i.e, 10 is big.

1.3 Multiple if( )

Definition: This concept is used to check series of conditions to perform the related tasks.

Example:
        class example_multiple_if
        {
            public void main()
            {
                int a = 5,b = 10,c = 20;
                if(a > b && a > c)
                {
                    System.out.println(a + " is big");
                }
                if(b > a && b > c)
                {
                    System.out.println(b + " is big");
                }
                if(c > a && c >  b)
                {
                    System.out.println(c + " is big");
                }
            }
        }

The above program will produce the output "20 is big" , since the last if( ) condition is only true, because the value of 'c = 20' is greater than 'a = 10' as well as 'b = 10', hence the statement within last if( ) condition executes and prints value of variable 'c' followed by message "is big" i.e., 20 is big.

1.4 if-else if( )

Definition: It is used to check series of conditions where only one condition body will execute and if all the conditions are false then the last else statement executes. It is also known as ladder of if-else-if.

Syntax:
        if(Condition1 or Relational expression1)
        {
            Statement1;
        }
        else if(Condition2 or Relational expression2)
        {
            Statement2;
        }
Or
        if(Condition1 or Relational expression1)
        {
            Statement1;
        }
        else if(Condition2 or Relational expression2)
        {
            Statement2;
        }
        else
        {
            Statement-n;
        }

Example: 
        class sample_if_else_if
        {
            public void main()
            {
                int a = 5,b = 10,c = 20;
                if(a > b && a > c)
                {
                    System.out.println(a + " is big");
                }
                else if(b > a && b > c)
                {
                    System.out.println(b + " is big");
                }
                else if(c > a && c > b)
                {
                    System.out.println(c + " is big");
                }
            }
        }
The above program will produce the output "20 is big" , since the last else-if condition is only true, because the value of 'c = 20' is greater than 'a = 5' as well as 'b = 10', hence the statement within last else-if condition executes and prints value of variable 'c' followed by message "is big" i.e., 20 is big.

1.5 Nested 'if( )' Statement

Definition: Presence of one or more if( ) statements inside one if( ) statement is known as nested if( ) statement.

Example: 
        class sample_nested_if
        {
            public void main()
            {
                int age = 20,height = 250;
                if(age > 18)
                    if(height > 200)
                        System.out.print("Eligible to play the game");
                    }
                }
                else
                {
                    System.out.print("Not eligible to play the game");
                }
            }
        }

In the above example as seen that every if( ) and else contains only one statement within itself, so the user may omit the curly braces '{ }' and writes as:
                if(age > 18)
                    if(height > 200)
                        System.out.print("Eligible to play the game");
                else
                    System.out.print("Not eligible to play the game");
But this is WRONG, because 'else' always goes with the nearest 'if( )' when there are no curly braces.

ADVICE: Always use curly braces with if( ) statements.

1.6 The Dangling 'if ( )' and 'else' Problem

The Java compiler always links the 'else' statement with immediately preceding 'if( )' statement. It means, in a nested 'if( )' statement when the number of 'if( )' statements are more than the number of else with missing scope of the 'if( )' statement then this ambiguous(having more than one possible meaning) situation leads to "Dangling else" problem. This problem arises because 'else' can not find its scope that the particular if( ) belongs to which if( ).

Definition: An ambiguous situation in which the number of 'if( )' statement appears more than the number of 'else' statement in nested-if( ) and the else cannot associate itself that which 'if( )' it belongs to, is known as dangling-else problem.

Example:
                if(m > 2)
                    if(n < 7)
                        System.out.print("m is greater than 2 and n is smaller than 7");
                else
                    System.out.print("m is less than 2");

The above example is a case of Dangling-else. Assume that,if ‘m=3' and ‘n=5',then the above code will
display the output "m is greater than 2 and n is smaller than 7".

But, if ‘m=3' and ‘n=9', then the above code will display the output "m is less than 2", means a wrong output because the value of ‘m=3'(means >2). This ambiguous problem arises because the 'else' statement is not able to associate that with which ‘if( )' it belongs to,i.e., Dangling-else problem.

Let's take ‘m=I' and ‘n=4', in this case the above code will not give any output even 'm is less than 2' because again the ‘else' statement is not able to associate that with which ‘if( )' it belongs to, i.e., Dangling-else problem.

Now, remember that, in case of absence of curly braces this problem will always arise, so always define the scope of 'if( )’ and ‘else’ statements to avoid any ambiguous situation.

2. Switch( ) - case Statement

Definition: The switch keyword is used to shift the control to multiple cases depending upon the value of variable or expression.

It is also known as multiple branching statement or user's choice statement. This concept is used to design a Menu Driven Program.

Syntax:
        switch(variable or expression)
        {
            case constant-1:
            Statements...;
            break;
            case constant-2:
            Statements...;
            ...
            ...
            case constant-n:
            Statement-n...;
            break;
            default:
        }

Note: Default statement is executed when NO match case is found.

Example:
        class sample_switch_case
        {
            public void main(int V)
            {
                switch(V)
                {
                    case 1:
                    System.out.println("Red");
                    break;
                    case 2:
                    System.out.println("Green");
                    break;
                    case 3:
                    System.out.println("Blue");
                    break;
                    default:
                    System.out.println("Wrong Choice");
                }
            }
        }

In the above switch block 'V' is a control variable on which case 1, case 2, case 3 and default clause will run. Every case is followed by a break statement, which terminates each case after the execution gets over.

If V = 1 then case 1 will run and display Red, for V = 2, the case 2 runs and displays Green, for V = 3, the case 3 runs and displays Blue and for any other value like, V = 0, V = -1,V = 4, V = -5, ....., the default clause will run and displays Wrong Choice. Finally the switch block terminates.

2.1 Fall Through

Definition: The absence of break statement in any one or more thanone case statements of the switch statement leads to "Fall Through" statement.

So that is it for the Decision Making Statements. Hope you find it useful and if you have any query do comment in the comment box and I will try to solve your query.

Thank You.
Decision Making Statements (if() , if_else() , Multiple if() , Nested if() and switch case statement ) (Java) Decision Making Statements (if() , if_else() , Multiple if() , Nested if() and switch case statement ) (Java) Reviewed by Get2Know on September 01, 2020 Rating: 5

No comments:

Business

Powered by Blogger.