Control Flow Statements in Java

In Java there are three types of control flow statements:

1. Decision making statements:  if, if else, nested if else
2. Looping statements: while, for, do-while
3. Branching statements: return, break, continue

if statement

  • It instructs the program to execute only certain part of the code if the condition is true.
  • If boolean value is true then statement1 will be executed.
Syntax:

if (boolean expr)
{
     statement 1:      //expr true
}
statement 2;


Flow Diagram
if
Fig: Flow diagram of if statement

if else statement

In this case, when if clause is false then else part will be executed.

Syntax:

if (boolean expr)
{
     statement 1;      //expr true
}
else
{
     statement 2;      //expr false
}


Flow Diagram
if else
Fig: Flow diagram of if else statement

Nested if else

Syntax:

if (boolean expr1)
{
     statement 1;      // expr1 true
}
else if (boolean expr2)
{
     Statement 2;      // expr 1 false and expr 2 true
}
else
{
     statement 3;      // expr 2 false
}


Example: Program for nested if else statement

Program to find largest number of three given numbers using if else.

class Test
{
     public static void main(String args[])
     {
          int x = 20;
          int y = 15;
          int z = 30;
          if (x > y)
          {
               if (x > z)
                    System.out.println("Largest number is: "+x);
               else
                    System.out.println("Largest number is: "+z);
          }
          else
          {
               if (y > z)
                    System.out.println("Largest number is: "+y);
               else
                    System.out.println("Largest number is: "+z);
          }
     }
}


Output:
Largest number is: 30

Switch Case Statement

It is type of selection mechanism that provides multi-way selection.

Flow Diagram

switch
Fig: Flow diagram of switch statement

Example: Simple program of switch statement

class SwitchDemo
{
     public static void main(String[] args)
     {
          int day = 6;
          String dayString;
          switch (day)
          {
               case 1:  dayString = "Sunday";
               break;
               case 2:  dayString = "Monday";
               break;
               case 3:  dayString = "Tuesday";
               break;
               case 4:  dayString = "Wednesday";
               break;
               case 5:  dayString = "Thursday";
               break;
               case 6:  dayString = "Friday";
               break;
               case 7:  dayString = "Saturday";
               break;
               default: dayString = "Invalid day";
               break;
          }
          System.out.println (dayString);
     }
}


Output:
Friday