Control Structures in Java

The control structures in java will be used to modify the sequential flow of a program. That is, the order in which the instructions on it are executed.

In a program, instructions are executed from top to bottom, and from left to right, depending on the order in which they appear. The different instruction blocks of our program will follow this sequential flow to execute the instructions. The instruction blocks shall be delimited by braces brackets:

Block {
instruction 1;
instruction 2; instruction 3;
instruction 4;
}

However, in some cases we will need to break this sequential flow. Reasons for that can be many, we may need to make a decision between one or several possible options, or maybe we need to perform some instructions several times. Therefore, we need certain structures that allow us to interrupt the sequential flow of the program, and move on to execute other blocks of code.

In this post, we will study the operation of the following control structures:

  • Decision making: if-then, if-then-else, switch.
  • Loop: for, while, do-while

Decision making structures

If Statement

The “if” statement is probably the most basic of flow control structures. The function evaluates a condition and executes a block of instructions in the event that the condition is true.

if statement flow

Exercise 1: Using if statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Enter the following code:
public class Div {   
public static void main(String args [ ] ){ 
   int num1,num2;
   num1 = 6; num2 = 3;
   if (num1%num2 ==0){
System.out.println ("The rest is: "+num1%num2);
System.out.println("The first number is divisible by the second");
        }
    }
}

Line 5: Contains the if statement, which evaluates the condition: num1%num2 ==0

If the condition is true, then the instructions within the if block (lines 6 and 7) are executed.

  1. Run the program, the result should be:
The rest is: 0
The first number is divisible by the second

if-else statement

The “if-else” statement provides a second path in the event that the condition was evaluated as false. That is, if it is false, we go on to execute another block of instructions.

if-else flow

Exercise 2: Using if-else statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Enter the following code:
public class Div {   
public static void main(String args [ ] ){ 
   int num1,num2;
   num1 = 6; num2 = 4;
   if (num1%num2 ==0){
System.out.println ("The rest is: "+num1%num2);
System.out.println("The first number is divisible by the second");
        } 
    else {
System.out.println("the first number is not divisible by the second");
        }
    }
}

Line 9: This line is new about the program we use when explaining the if statement. We use the reserved word else to define the block of instructions to be executed when the evaluation of the if condition (num1%num2 ==0)  is false.

  1. Run the program. You should get the result:
the first number is not divisible by the second

if-else-if statement

With this type of instruction, we use several conditions to check. The syntax is:

if (condition-1)
  instruction block-1
  else if (condición-2)
    instruction block-2
  else if (condición-3)
    instruction block-3

Exercise 3: Using if-else-if statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Enter the following code:
public class Using_ifelseif{
public static void main(String []args){
    String day;
    day = "Sunday";
    if (day.equals("Monday")){
    System.out.println("Ufff!, just starting the week");
    }
    else if (day.equals("Wednesday")){
        System.out.println("In the middle of the week");
    }
    else if (day.equals("Friday")){
        System.out.println("Tomorrow is weekend");
    }
    else if(day.equals("Saturday")|| day.equals("Sunday")){
        System.out.println("Enjoy the weekend");
    }
    else {
        System.out.println("have a nice day");
    }
    }
}

Line 3: Declaration of variable day of type String.

Line 4: Initialization of the variable day. We use this variable to practice with the different if statements.

Line 5: First if statement.

Line 14: it evaluates an expression with the operator “||” (logical operator OR). If one of the two operands is true the full expression is evaluated as true.

  1. Execute the program. The result will be:
Enjoy the weekend
  1. Let’s type another code to better understand how these control statement works. We will compare the use of the “else if” statement with the use of the “if” statement:
public class PlayingIf{
    
public static void main(String []args){
    int number;
    number = 7;
    
//Usando else if
    System.out.println ("Using the else if statement");
    if (number > 2){
        System.out.println(number + " is greater than 2");
    }
    else if (number >5){
        System.out.println(number + " is greater than 5");
    }
    else if (number == 7){
        System.out.println("The number is 7");
    }
    
//Using the if statement
    System.out.println ("-------------");
    System.out.println ("Using only the if statement");
    if (number > 2){
        System.out.println(number + " is greater than 2");
    }
    if (number >5){
        System.out.println(number + " is greater than 5");
    }
    if (number == 7){
        System.out.println("The number is 7");
    }
    }
}

Line 6 to Line 15: We perform several comparisons using the else if statement. When one of the conditions is true, the instructions block of that condition will be executed and the rest of the conditions will not even be evaluated.

Line 17 to 27: On this occasion, we evaluate the same conditions as before, but using only the if statement. The different conditions are evaluated and the block instructions are executed if the condition is true. In this case, all conditions are evaluated.

  1. Run the program and the result will be:
Using the else if statement
7 is greater than 2
-------------
Using only the if statement
7 is greater than 2
7 is greater than 5
The number is 7

Switch statement

This statement is used to select a block of instructions to execute, based on the value of an expression. It works as follows:

  • The expression of the switch statement is evaluated.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the corresponding block is executed.
  • Break and default statements are optional

The syntax is:

switch(expression) {
  case x:
    instruction block
  break;
  case y:
    instruction block
  break;
  default:
    instruction block
}

Let’s see how it works on an example.

Exercise 4: Using switch statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Enter the following code:
public class UsingSwitch{
public static void main(String []args){
    String day;
    day = "Sunday";
    switch (day){
        case "Monday":
            System.out.println("Ufff!, may the force be with you");
        break;
        case "Wednesday":
            System.out.println("We're in the middle of the week");
        break;
        case "Friday":
            System.out.println("Tomorrow starts the weekend");
        break;
        case "Saturday": case "Sunday":
            System.out.println("Enjoy the weekend");
        break;
        default:
            System.out.println("Have a nice day");
        break;
    }
}
}

Line 5: The switch statement. The expression that evaluates the value of the day String.

Line 7: Instruction that would be executed in case it was Monday.

Line 10: Instruction that would be executed in case it was Wednesday.

Line 19: Instruction that would be executed in the event that none of the blocks of previous sentences were executed.

  1. If you run the program you will get the following result
Enjoy the weekend

Loop statements

Java has some statements that recurrently execute a block of code, as long as a certain condition is met. These sentences are:

  • for
  • while
  • do-while

for statement

The for statement creates a loop that runs as long as a certain condition is true. It handles an iterator that changes its value each time the loop is executed. We will finally get out of this when the condition becomes false.

for statement flow

The syntax:

for (iterator initialization; condition; iterator update)
   < instruction lock>

Let’s look at it in an example.

Exercise 5: Using for statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Enter the following code:
public class Usingfor {
public static void main(String args[]) {
    for (int iterator=0; iterator<10;iterator++){
        System.out.println("The iterator or counter is: "+iterator);
    }
}
}

Line 3: The for statement where we use the iterator variable of type int. The condition we evaluate is: iterator<10. And the iterator is incremented by one each time the instruction block is executed.

Line 4: We paint the value of the iterator on the screen.

  1. If we now execute the Code, we will obtain the following result:
The iterator or counter is: 0
The iterator or counter is: 1
The iterator or counter is: 2
The iterator or counter is: 3
The iterator or counter is: 4
The iterator or counter is: 5
The iterator or counter is: 6
The iterator or counter is: 7
The iterator or counter is: 8
The iterator or counter is: 9
  1. Change the operator update. Try the following code:
public class Usingfor {
public static void main(String args[]) {
    for (int iterator=0; iterator<10;iterator=iterator+3){
        System.out.println("The iterator or counter is: "+iterator);
    }
}
}

Line 3: The for statement. We have changed the iterator update, now, every time the loop instructions are executed, the iterator will be incremented by 3 instead of by 1.

  1. Run the program. You will get the following result:
The iterator or counter is: 0
The iterator or counter is: 3
The iterator or counter is: 6
The iterator or counter is: 9

while statement

The while statement remains in a loop executing a block of code as long as a specified condition is true

while statement flow

And the syntax is:

while (condition) {
   < instruction block >
}

Exercise 6: Using while statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Enter the following code:
public class UsingWhile {
public static void main(String args[]) {
    int number=15;
    while (number>2){
        System.out.println("The number is "+number);
        number = number -3;
    }
}
}

Line 3: The variable number is initialized to 15.

Line 4: The while statement. The condition number>2 is evaluated, and if it is true the instructions are executed within the while block. If it’s not, we get out of the while loop.

Line 6: The value of the variable number is decreased by 3. If we did not modify the value of this variable within the block, the program would enter an infinite loop, it would always be executing the instructions within the while loop.

  1. If you run the program, you will get the following result:
The number is 15
The number is 12
The number is 9
The number is 6
The number is 3

do-while statement

Similar to the while block, but the instruction block is executed at least once, since the condition evaluation is done after each execution of the instruction block.

do-while flow

And the sintax is:

do {
   <instructions block>
} while (condition)

To better appreciate the difference with the while statement, we will use the same example used when explaining while statement, but changing it to do-while.

Exercise 7: Using do-while statement

  1. Open the online compiler: jdoodle (my suggestion)
  2. Change the Code of the activity performed for the while statement, so that the condition of the while loop is false from the beginning and in this way, the while loop is never executed
public class UsingWhile {
public static void main(String args[]) {
    int number=1;
    while (number>2){
        System.out.println("The number is "+number);
        number = number -3;
    }
}
}
  1. If you run the program, you will get nothing as result. We found the while loop has not been executed once.
  2. Now change the while loop for a do-while loop:
public class UsingWhile {
public static void main(String args[]) {
    int number=1;
    do{
        System.out.println("The number is "+number);
        number = number -3;
    }while(number>2);
}
}
  1. If you run the program, the result is:
The number is 1
  1. It can be seen that the instruction block has been executed at least once, although the condition of the do-while loop has never become true

NOTE:

This post is part of the “Java” collection that reproduces the notes of the class I teach on the subject at ESIC. You can see the index of this collection  here.

Leave a Reply

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