[Complete Guide] Control Flow Statements in Java with Coding Examples

[Complete Guide] Control Flow Statements in Java with Coding Examples

Statements are the lines of code that direct the next action to be performed. Control flow statements in Java as the name suggests are the kind of statements that decide the flow of operation of any piece of code. The control flow statements either pass over or advance statements to change the state of the program, which can be done by making use of decision making, looping, and branching statements.

Control Flow Statements in Java:

In this tutorial, we will be learning about,

Table of content:

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

Decision-making Statements:

The decision-making statements are also considered to be selection statements which opt different paths of execution based on the evaluation of a conditional test expression or statement.  The varied forms of decision making control flow statements include,

  • If then
  • If then else
  • Nested if..else
  • Switch

if Statement:

Let us have a look at the distinct forms of if-then and if-then-else statements.

if-then statement if-then-else statement Nested if-then-else
if(condition){
/*executes the statements below if the condition expression returns true */

statement_1;
statement_2;
}

 

if(condition){
/*executes the statements below if the condition expression returns true */

statement_1;
}

else{

/*executes the statements below if the condition is false*/
statement_2;
}

 

if(condition_1){
/*executes the statements below if the condition expression returns true */

statement_1;
...
}

else if(condition_2){
/*executes the statements below if the condition expression returns true */

statement_2;
}

else{
/*executes the statements below if the condition is false*/

statement_3;
}

 

Let’s sneak peek into how these selection statements can be used out in our programs.

Example for if-else:

public class ifElseExample{
public static void main(String args[]){

    int x,y;
    x=15;
    y=10;

    if(x<y){
        System.out.println("X=" +x+ " and Y="  +y);
        System.out.println("X is less than Y");
    }

    else{
        System.out.println("X=" +x+ " and Y="  +y);
        System.out.println("X is greater than Y");
    }             
}
}

Output:

X=15 and Y =10
X is greater than Y.

Example for the if-else ladder:

public class ifElseLadderExample{
public static void main(String args[]){

    int x=15,y=10,z=20;

    if(x<y && x<z){
      System.out.println("X=" +x+ " , Y="  +y+ " and Z=" +z);
      System.out.println("X is less than Y & Z");
    }

    else if(y<x && y<z){
      System.out.println("X=" +x+ " , Y="  +y+ " and Z=" +z);
      System.out.println("Y is less than X and Z");
    }             

    else{
      System.out.println("X=" +x+ " , Y="  +y+ " and Z=" +z);
      System.out.println("Z is less than X and Y");
    }
}
}

Output:

X=15, Y=10, Z=20
Y is less than X and Z

The switch statement:

In contrast, the switch statement provides diverse options to execute statements in a program. The selection of the right option for statement execution is determined by the expression placed in between the parenthesis after switch keyword. The expression in the parenthesis must be of the type int, char, byte or short. The switch can work well with enumerated data types, String class and few other wrapper classes available in Java.

The principal form of the writing switch case statement is as follows:

switch(expression){

case_1: statement_1;
case_2: statement_2;
....
....
case_n: statement_n;
}

In case, if any of the expressions don’t match the case-labels then a default statement is executed. A switch block can have more than one case or default labels.

We can even use the jumping statement like break to terminate the sequence of execution of statements in corresponding case values. The use of break statement is of optional use in the switch block.

Let’s try out a simple example of switch block without break statement:

public class SwitchCaseExample1 {
public static void main(String args[]){
      int val=2;
      switch(val)
      {
                 case 1:
                   System.out.println("Case1 ");
                 case 2:
                   System.out.println("Case2 ");
                 case 3:
                   System.out.println("Case3 ");
                 default:
                   System.out.println("Default case ");
      }
   }
}

Output:

Case 2
Case 3
Default case

In the next example let’s look into how switch block works with a break statement.

public class SwitchCaseExample2 {
   public static void main(String args[]){

      int month=7;

      switch(month)
      {
                 case 1:
                   System.out.println("Happy January! ");
                   break;

                 case 2:
                   System.out.println("Happy February! ");
                   break;

                 case 3:
                   System.out.println("Happy March! ");
                   break;

                 case 4:
                   System.out.println("Happy April! ");
                   break;

                 case 5:
                   System.out.println("Happy May! ");
                   break;

                 case 6:
                   System.out.println("Happy June! ");
                   break;

                 case 7:
                   System.out.println("Happy July! ");
                   break;

                 case 8:
                   System.out.println("Happy August! ");
                   break;

                 case 9:
                   System.out.println("Happy September! ");
                   break;

                 case 10:
                   System.out.println("Happy October! ");
                   break;

                 case 11:
                   System.out.println("Happy November! ");
                   break;

                 case 12:
                   System.out.println("Happy December! ");
                   break;

                 default:
                   System.out.println("Invalid month ");
                   break;
      }
   }
}

Output:

Happy July!

Also, read Logical / Conditional Operators in Java. With this you can set different conditions in your Java programming.

Looping Statements:

The continuous repetition of a set of statements until a certain condition is satisfied can be described as the behavior of a loop. The looping statements allow us to skip writing repetitive code. The repetition of same piece of code numerous times can also be called as an iteration. As mentioned earlier, Java provides us with three kinds of looping/iteration statements namely, while, do-while and for the loop.

Iteration Statement Type Principal Syntax Description
while
while(condition){
statement_1;
....
....
statement_n;
}
The while statement evaluates the condition in the parenthesis. If the condition evaluates to true then, the statement(s) in the while block is executed. The while statement persists to test the conditional statement and execute the statement(s) in the block until the condition evaluates to false.
do-while
do{
statement_1;
...
...
statement_n;
}while(condition);
The do-while looping statement evaluates the statements inside the body of the do-while block first and then evaluates the condition specified in parenthesis after the while keyword. If the condition evaluates true then next iteration is executed else no iteration takes place.
for
for(initialization; termination_condition; change_of_state)
{
statement(s);
....
....
}

 

The for loop statement consists 3 segments in one statement, i.e., initialization, termination condition and change of state expression.

i. The initialization expression initializes the value of loop

ii. The termination expression when evaluates to false the loop terminates its execution.

iii. The change of state expression can be any expression (increment/decrement) that invokes change in expression’s value. It is invoked after every iteration of the loop.

Note that the basic difference between while and do-while loop is that the conditional expression is evaluated at the end in the do-while loop and do-while loop statements execute at least once.

Let us look one by one example of looping statements.

While loop Example:

public class WhileExample {
    public static void main(String[] args){

        int count = 1;

        while (count <= 5) {
            System.out.println(count);
            count++;
        }
    }
}

Output:

1
2
3
4
5

Do-while loop Example:

public class DoWhileExample {
    public static void main(String[] args){

        int i = 5;
        do
        {
            System.out.println(i);
            i--;
        }while (i > 0) ;
    }
}

Output:

5
4
3
2
1

For loop Example:

public class ForLoopExample {
    public static void main(String[] args){

        int i;

        for(i=1;i<=5;i++){
            System.out.println(i);
        }
    }
}

Output:

1
2
3
4
5

Branching Statements:

The branching statements unconditionally shift the control of the program to another segment of the program. The branching statements are also referred as the jumping statements. The distinctive forms of jumping statements are break, continue and return.

The break statement:

It instructs the control flow statements to terminate the execution of current block and shift to the first statement after the block. It is used in two forms labeled and unlabelled. The unlabelled form is used for looping statement blocks and the switch statement(s).

The principal syntax of break statement is: break label;

Now, taking a look at how labelled and unlabelled break statements are used:

Labelled ‘break’ statement Unlabelled ‘break’ statement
Example:

Outer:

for(int i=0; i < 5 ; i++) {
for(int j = 1; j < 5;j++) 
{   
System.out.println(“i:” + i + “, j:” + j);

if(i == 3)
break Outer;
}
}

Description:

When the condition i=3 returns true then the loop labeled ‘Outer’ is terminated.

Example:

for(int i =0; i < 5 ; i++)
{
System.out.println(“i : “ + i);

if(i == 2)
break;
}

 

Description:

When the condition i=2 turns out to be true, then the for loop automatically terminates.

The continue statement:

It instructs the control flow statements to skip the execution of the current line of code and move to the next block of code. It is also used in two forms labeled and unlabelled. The principal syntax of continue statement is: continue label;

Now, taking a look at how labeled and unlabelled continue statements are used:

Labelled ‘continue’ statement Unlabelled ‘continue’ statement
Example:

Outer:

for(int i=0; i < 5 ; i++) {
for(int j = 1; j < 5;j++) 
{
if(i == 3) {
continue Outer;
System.out.println(“i:” + i + “, j:” + j);
}
}
}

Description:

When the condition i=3 returns true then the loop labelled ‘Outer’ is skipped and the statements in the inner loop get executed.

Example:

for(int i=0; i < 5 ; i++) {
for(int j = 1; j < 5;j++) 
{
if(i == 2) {
continue;
System.out.println(“i:” + i + “, j:” + j);
}
}
}

 

Description:

When the condition i=2 turns out to be true, then continue statement skips to the last line of code in the innermost loop.

The return statement:

It instructs the block of code to exit and return to the method it was invoked from. It comes in two forms, one which returns some value and the other that doesn’t return any value.

Example:

return num; // returns the value stored in variable ‘num’

Here, the type of returned value should be the same as that it is initially declared in the program or to the type of method.

return; // doesn’t return anything & is used with void functions

To summarize, in this tutorial we have learned how control is transferred from one block of the program to another by employing the different kinds of control flow statements, which can be selection statements, iteration statements or jumping statements. Do try out various kinds of examples to better understand the working of control flow statements in Java.

Happy Learning!



2 Comments

  1. The codes are very well explained..nicely elaborated theory.. you’re making learning java like a cakewalk!

Leave a Reply

Your email address will not be published. Required fields are marked *