CHAPTER 4

CONTROL STRUCTURES

In Chapter 3, we saw a few simple statements. In a program, these statements are executed one after the other. However, these statements are not sufficient to effectively solve the problems. To solve these problems, flow control statements are used. When we use them, statement to be executed need not be the very next statement. This gives tremendous power to the code.

Java supports many flow control statements. We can group these statements in the following manner.

  1. The first group consists of decision-making statements. Examples are
    If-else and switch-case statements.
  2. The second group consists of looping statements. Examples are
    while, do-while, and for statements.
  3. The third group consists of branching statements Examples are
    break, continue, label, and return statements.
  4. The last group consists of exception handling statements. Examples are
    Try-catch-finally and throw statements.

Let us start our study with a simple if statement.

4.1 Simple If Statement

Right from our first exam, we are faced with pass or fail dilemma. If we get minimum marks, then we pass. If we have enough money, we may go to the theatre. The action depends on a condition. This is characterized in if statement. Its general syntax is as follows:

 if ( condition ) statement;

It can be described as follows:

  • It starts with keyword if.
  • It is followed by a condition, which is a Boolean expression.
  • This condition has to be put in round brackets.
  • A statement follows it.
  • As usual, semicolon marks the end of statement.
  • A block, meaning a group of statements enclosed in curly brackets, is considered as a (single) statement from grammar point of view.
Figure 4.1 If Statement

Figure 4.1 If Statement

Figure 4.1 describes the if statement pictorially.

When a computer executes this statement, it first evaluates the condition. If it evaluates to true, computer executes the statement. If the condition fails, no action is taken.

4.2 If-Else Statement

Right from our first exam, we are faced with pass or fail dilemma. If we get more than specified marks, we pass otherwise we fail. There are two different actions, depending on a Boolean condition. This is characterized in if-else statement. Its general syntax is as follows:

 if ( condition ) statement1 ;

    else statement2 ;

It can be described as follows:

  • It starts with keyword if.
  • It is followed by a condition, which is a Boolean expression.
  • This condition has to be put in round brackets.
  • It is followed by a statement 1.
  • As usual, semicolon marks the end of this statement.
  • Next comes keyword else.
  • It is followed by a statement 2.
  • Finally, semicolon marks the end of this statement.
  • A block, meaning a group of statements enclosed in curly brackets, is considered as a (single) statement.

Figure 4.2 pictorially illustrates this description.

When a computer executes this statement, it first evaluates the condition. If it evaluates to true, the computer executes statement1. If the condition fails, it executes statement2.

Figure 4.2 If-Else Statement

Figure 4.2 If-Else Statement

Now let us study a simple program.

Problem: Write a program to read marks out of 100 and declare result. The rules are as follows:

 

  60 or more marks first class
  50 to 59 marks second class
  40 to 49 marks pass class
  less than 40 marks fail

Solution: See Program 4.1.

 

PROGRAM 4.1 If Statement I

 //     ifthen1.java

 class ifthen1

   { public static void main(String args[])

       {  int marks = 55 ;

          if (marks >=50 )

                if (marks >= 60)

                        System.out.println(“First class”);

                   else System.out.println(“Second class”);

            else

                if (marks >= 40)

                        System.out.println(“Pass class”);

                  else System.out.println(“Fails”);

      }

 }

If you run this program, you will get the following output.

 

Output

 Second class

4.3 Switch-Case Statement

Many times, specific actions take place for specific conditions (cases). Coding becomes complicated on using if-else statement. To help the programmers, language supports this new construct, that is, switch-case statement. There are some variations in this statement. Hence, let us study it step by step.

In the simplest form, the statement appears as follows.

 switch ( n )

  { case 1 : statement_1;

      case 2 : statement_2;

      case 3 : statement_4;

      case 4 : statement_4;

    }

Figure 4.3 illustrates the logic of this statement.

When control enters the switch construct, it tries to match n with values in case clause. If any value matches, then corresponding statement is executed. Thereafter, all the statements (without caring for matching case) are executed. It goes without saying that if there is no match, no statement is executed.

It is understood that n stands for any variable or expression of type byte, short, int, or char. It cannot be of type long.

Figure 4.3 Switch-Case Simple Form

Figure 4.3 Switch-Case Simple Form

Let us try this with a program.

Problem: Write a program to demonstrate the general form of switch-case statement.

Solution: See Program 4.2.

 

PROGRAM 4.2 Switch-Case Statement Simple Form

 //     switch5.java

 class switch5

 { public static void main(String args[])

   { int n = 2;

     System.out.println("<---switch5.java--->");

     switch (n)

       { case 1 : System.out.println("I am 1");

         case 2 : System.out.println("I am 2");

         case 3 : System.out.println("I am 3");

         case 4 : System.out.println("I am 4");

       }

     System.out.println(“Out of switch case statement”);

   }

 };

If you run this program, you will get the following output.

 

Output

 <---switch5.java--->

 I am 2

 I am 3

 I am 4

 Out of switch case statement

Please note that in Program 4.2, n was 2. After printing I am 2 the program printed few more lines.

Though we have said statement_2, actually there can be more than one statement. The nomenclature is only to indicate that this statement is to be executed when case matches to 2.

Another point to note that identifier n stands for any variable or expression, which represents integral value. It means a character expression is also accepted.

In a rational use of any selection statement, we would like to execute only specific statements. If case is 2, we would like only statement_2 to be executed, and not the remaining statements thereafter. By this time, you must have guessed correctly that it is quite simple to achieve; just add “break” statement after every statement.

The new form of switch-case statement is more useful than the simple form. It will appear as follows:

switch ( int_value )

                 { case value1 : statement_1; break;

           case value2 : statement_2; break;

           case value3 : statement_4; break;

                   case value4 : statement_4; break;

                 }

Figure 4.4 illustrates the logic of this statement.

Figure 4.4 Switch-Case Useful Form

Figure 4.4 Switch-Case Useful Form

Let us study a simple program using “switch” statement (see Program 4.3 in action).

Problem: Write a program to simulate calculator. Assume operands as two given integers. Operation should be performed as specified.

Solution: In this program, we will use simple arithmetic operations like addition subtraction, multiplication, and division. For the sake of simplicity, the action character will be specified in a program (instead of being accepted from the keyboard; see Program 4.3).

 

PROGRAM 4.3 Calculator Simulation

 //     switch8.java

 class switch8

 { public static void main(String args[])

   {  int i=3,j=7,k=0 ;

      System.out.println("---switch8.java---");

      // specifying input

      char ch ='*' ;

      switch(ch)

         {  case '+' : k = i+j ;break;

            case '-' : k = i-j ;break;

            case '*' : k = i*j ;break;

            case '/' : k = i/j ;break;

         };

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

      // else System.out.println("Invalid date");

   }

 }

If you run this program, you will get the following output.

 

Output

 ---switch8.java---

 k= 21

Figure 4.5 Switch-Case Most Practical Form

Figure 4.5 Switch-Case Most Practical Form

We can add a default clause (case) to this statement. When the value of switch expression does not match with any of the case values, statements in default clause are executed.

You may wonder what is the necessity of “default clause”. In a properly designed program, all cases must be considered. If something is missing by error, there should be some indication of it. A small error message in default clause will be helpful in debugging.

Alternately, if some assignment or action pertains to all remaining cases, we can use default clause. Hence, most practical form of a switch-case statement is one having both break and default clause.

switch ( int_value )

    { case value1 : statement_1; break;

           case value2 : statement_2; break;

           case value3 : statement_4; break;

      case value4 : statement_4; break;

           default : default_satement; // note no break required here.

    }

Figure 4.5 illustrates the most practical form of switch-case statement.

Problem: Write a program to decide whether a given date is valid date for a non-leap year. Read only date and month. Use switch statement for maximum days of a month. Use default clause for valid value of the month.

Solution: In English calendar, number of days is defined for every month. We will use case values 1 to 12 for months January to December. Checking a valid date means checking two things. First, value of month is between 1 and 12, and second, date is within 1 and max-value for that month (see Program 4.4).

 

PROGRAM 4.4 Switch with Default

 //     switch6.java

 class switch6

 { public static void main(String args[])

 {   boolean result = true ; // boolean answer;

     int maxdays= 0 ;

     System.out.println(“<---switch6.java--->”);

     // specifying input

     int date = 3 ;

     int month = 14 ; // invalid month

          { switch(month)

            { case 1 : maxdays = 31;break;

              case 2 : maxdays = 28;break;

              case 3 : maxdays = 31;break;

              case 4 : maxdays = 30;break;

              case 5 : maxdays = 31;break;

              case 6 : maxdays = 30;break;

              case 7 : maxdays = 31;break;

              case 8 : maxdays = 31;break;

              case 9 : maxdays = 30;break;

              case 10 : maxdays = 31; break;

              case 11 : maxdays = 30; break;

              case 12 : maxdays = 31; break;

             default : result = false ;

            };

           if (date > maxdays) result = false ;

          };

    if ( result ) System.out.println(“Valid date”);

         else System.out.println(“Invalid date”);

   }

 }

If you run this program, you will get the following output.

 

Output

 <---switch6.java--->

 Invalid date

Let us try one more program.

If the action taken is identical, for certain cases, we can use the absence of break with convenience. We have to write the action only once. Let us see with the concrete example.

Problem: Rewrite Program 4.4 on valid date with different style.

Solution: See Program 4.5.

 

PROGRAM 4.5 Switch Statement Different Style

 //     switch4.java

 class switch4

 { public static void main(String args[])

   {  boolean result = true ; // boolean answer;

      int maxdays= 0 ;

      System.out.println(“---switch4.java---”);

      // specifying input

      int date = 31 ;

      int month = 8 ;

      if ( (month < 1) || (month > 12) || (date<1) )

               result = false;

          else

           {   switch(month)

               { case 2 : maxdays = 28;break;

                 case 1 : ;

                 case 3 : ;

                 case 5 : ;

                 case 7 : ;

                 case 8 : ;

                 case 10 : ;

                 case 12 : maxdays = 31; break;

                 case 4 : ;

                 case 6 : ;

                 case 9 : ;

                 case 11 : maxdays = 30; break;

              };

            if (date > maxdays) result = false ;

          };

      if ( result ) System.out.println(“Valid date”);

           else System.out.println(“Invalid date”);

   }

 }

If you run this program, you will get the following output.

 

Output

 ---switch4.java---

 Valid date

In Program 4.5, we have used data value for month as 8. When switch statement is executed, control comes up to case 8. There is no executable statement against 8. Hence, control passes to case 10 and subsequently to case 12. It executes assignment max-days = 31 and breaks. It means that when the value of the month is anything like 1, 3, and 5 there is only one action that is max-days = 31.

Advance Note

In addition to basic types, the switch variable can be of a wrapper class like character, byte, short, and integer. It can be also of any enumerated type. Wrapper classes and enumerated types are discussed later in the book.

Keywords

case, default, if statement, if-else statement, switch, switch-case statement

RuleBook

switch default Default clause is optional in Java
switch expression Switch expression can be of basic type byte, short, int or character. It can be also be Wrapper class type like Character, Byte, Short, or Integer. It can be also of any enumerated type

Review Questions

  1. If there are many if clauses before the first else, to which if clause the else belongs?
  2. Is presence of switch-case statement a must in a programming language?
  3. Can any case statement be replaced by an if statement?
  4. Can case statement substitute for an if statement?

Exercises

  1. Given the temperature, print whether water will be in solid, liquid, or vapour form.
  2. Find roots of a given quadratic equation.
  3. Find if integer is odd or even.
  4. Find the largest of three integers.
  5. Find the largest of four given real numbers.
  6. Find if a given point lies in a given circle or not.
  7. State whether the following program will compile. If yes, describe the output. If no, give reasons and suggest minimum changes in the code.

     **************************************

     //     switch2.java

     class switch2

     { public static void main(String args[])

       {  boolean result = true ; // boolean answer;

          int maxdays= 0 ;

          System.out.println(“---switch2.java---“);

          // specifying input

          int date = 31 ;

          int month = 4 ;

          if ( (month < 1) || (month > 12) || (date<1) )

                 result = false;

             else

              {  switch(month)

                 {  case 1 : maxdays = 31;break;

                    case 2 : maxdays = 28;break;

                    case 3 : maxdays = 31;break;

                    case 4 : maxdays = 30;break;

                    case 5 : maxdays = 31;break;

                    case 6 : maxdays = 30;break;

                    case 7 : maxdays = 31;break;

                    case 8 : maxdays = 31;break;

                    case 9 : maxdays = 30;break;

                    case 10 : maxdays = 31; break;;

                    case 11 : maxdays = 30; break;

                    case 12 : maxdays = 31; break;

                 };

               if (date > maxdays) result = false ;

              };

        if ( result ) System.out.println(“Valid date”);

             else System.out.println(“Invalid date”);

       }

     }

    **************************************

    In this program, input was specified in the program itself. Consider that this program is modified to read the date and the month from keyboard. Will the program give correct result in that case?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.150.123