Control Statements in Java

Control statements are an essential part of any programming language. They allow us to control the flow of our program, determining which lines of code are executed and in what order. In this blog post, we’ll be focusing on control statements in Java.

Java has three main types of control statements:

  1. Conditional statements – These statements allow us to execute a block of code only if a certain condition is met. Java has two types of conditional statements: the if statement and the switch statement.
  2. Loop statements – These statements allow us to execute a block of code multiple times. Java has three types of loop statements: the for loop, the while loop, and the do-while loop.
  3. Transfer statements – These statements allow us to transfer control from one part of your program to another. Java has three types of transfer statements: the break statement, the continue statement, and the return statement.

Let’s take a closer look at each of these control statements in Java.

Conditional statements

Java has two types of conditional statements: the if statement and the switch statement.

The if statement

The if statement allows us to execute a block of code only if a certain condition is true. Here is the general syntax for an if statement in Java:

if (condition) {
   // code to be executed if condition is true
}

We can also include an else clause to execute a block of code if the condition is false:

if (condition) {
   // code to be executed if condition is true
} else {
   // code to be executed if condition is false
}

We can also include multiple else if clauses to check for multiple conditions:

if (condition1) {
   // code to be executed if condition1 is true
} else if (condition2) {
   // code to be executed if condition1 is false and condition2 is true
} else {
   // code to be executed if condition1 and condition2 are false
}

The switch statement

The switch statement allows us to execute a block of code based on the value of a variable. Here is the general syntax for a switch statement in Java:

switch (variable) {
   case value1:
      // code to be executed if variable is equal to value1
      break;
   case value2:
      // code to be executed if variable is equal to value2
      break;
   ...
   default:
      // code to be executed if variable is none of the above values
}

The break statement is used to exit the switch statement once a matching case is found. If we omit the break statement, the code will continue to be executed until the end of the switch statement.

Loop statements

The for loop

The for loop is used to execute a block of code a specified number of times. Here is the general syntax for a for loop in Java:

for (initialization; condition; increment) {
   // code to be executed
}

The initialization section is executed once at the beginning of the loop. It is typically used to initialize a loop variable.

The condition is checked before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop is terminated.

The increment section is executed at the end of each iteration of the loop. It is typically used to update the loop variable.

Here is an example of a for loop that counts from 1 to 10:

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

This for loop will print the numbers 1 through 10 to the console.

The while loop

The while loop is used to execute a block of code as long as a certain condition is true. Here is the general syntax for a while loop in Java:

while (condition) {
   // code to be executed
}

It’s important to include a way to change the value of the condition inside the loop, or else the loop will become an infinite loop and your program will never end.

The do-while loop

The do-while loop is similar to the while loop, except that it is guaranteed to execute at least once. Here is the general syntax for a do-while loop in Java:

do {
   // code to be executed
} while (condition);

Like the while loop, it’s important to include a way to change the value of the condition inside the loop to prevent infinite loops.

Transfer statements

Java has three types of transfer statements: the break statement, the continue statement, and the return statement.

The break statement

The break statement in Java is used to exit a loop early. It can be used within a while, do-while, or for loop.

Example of using the break statement within a for loop is given below:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
}

In this example, the loop will iterate from 0 to 4, printing each number to the console. When the loop variable i reaches 5, the if statement will evaluate to true and the break statement will be executed, causing the loop to exit and the program to continue with the next statement after the loop.

We can also use label with break statement. Let’s see an example below:

 outerloop:
   for (int i = 0; i < 3; i++) {
     innerloop:
       for (int j = 0; j < 3; j++) {
         if (i == 1 && j == 1) {
           break outerloop;
         }
         System.out.println("i = " + i + "; j = " + j);
       }
   }

In this example, when i=1, j=1 the outerloop will break. The output of the above code will be like:

i = 0; j = 0
i = 0; j = 1
i = 0; j = 2
i = 1; j = 0

Similarly, we can use break statement within a while loop as well. Let’s see an example below:

int i = 0;
while (true) {
    if (i == 5) {
        break;
    }
    System.out.println(i);
    i++;
}

In this example, the while loop will run indefinitely (since the condition is always true) but the break statement will cause the loop to exit when the variable i reaches 5. This will prevent the program from running indefinitely and causing an infinite loop.

It’s worth noting that the break statement can also be used to exit a switch statement early. When a break statement is encountered within a switch block, the program will exit the block and continue with the next statement after the switch.

The continue statement

The continue statement is used to skip the rest of the current iteration of a loop and move on to the next iteration. When the continue statement is encountered inside a loop, control is transferred to the end of the current iteration and the loop continues with the next iteration.

Let’s take an example of the following code using continue statemtn in for loop:

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;
    }
    System.out.println(i);
}

Output of the above code will look like:

1
3
5
7
9

In the example code above, the loop iterates from 0 to 9, but the continue statement causes the program to skip over any iteration where i is an even number. This means that only odd numbers will be printed to the console. The if statement with the continue statement inside is used to check if the current iteration variable is an even number, if yes the current iteration will be skipped and next iteration will begin.

We can also use continue statement with label. The example of continue statement with label is given below:

 outerloop:
   for (int i = 0; i < 3; i++) {
     innerloop:
       for (int j = 0; j < 3; j++) {
         if (i == 1 && j == 1) {
           continue outerloop;
         }
         System.out.println("i = " + i + "; j = " + j);
       }
   }

In the example above, when i=1, j=1 the outerloop will continue, the current iteration of outerloop will be skipped. Hence the output of the above program will be:


i = 0; j = 0
i = 0; j = 1
i = 0; j = 2
i = 2; j = 0
i = 2; j = 1
i = 2; j = 2

It’s important to use continue statement properly and in the appropriate context. Using it in the wrong place can lead to unexpected behavior and make the code more difficult to understand.

The return statement

The return statement in Java is used to exit a method and return a value to the calling method. Here’s an example of a simple method that uses the return statement:

public int add(int a, int b) {
    int sum = a + b;
    return sum;
}

In the example above, the add method takes two integer parameters, a and b, and adds them together. The result is stored in the variable sum, which is then returned to the calling method using the return statement. This method can be called from another part of the program like this:

int result = add(2, 3);

And the output of this code will be 5.

The return statement within a for loop

The return statement can be used within a loop in Java to exit the loop early and return a value to the calling method.

Following is an example of a method that uses a for loop and the return statement to search for a specific value in an array:

public int findValue(int[] array, int target) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == target) {
            return i;
        }
    }
    return -1;
}

In the example above, the findValue method takes two parameters: an array of integers, array, and an integer, target. The method uses a for loop to iterate through the elements of the array and checks if the current element is equal to the target using the if statement. If it finds a match, the method returns the index of the matching element using the return statement. If the target value is not found in the array, the method returns -1.

The return statement within a while loop

Following is an example of a method that uses a while loop and the return statement to search for a specific value in a list:

public boolean containsValue(List<Integer> list, int target) {
    int i = 0;
    while (i < list.size()) {
        if (list.get(i) == target) {
            return true;
        }
        i++;
    }
    return false;
}

In the example above, the containsValue method takes a list of integers and an integer value as a target, it uses a while loop to iterate through the elements of the list and checks if the current element is equal to the target. If it finds a match, the method returns true using the return statement. If the target value is not found in the list, the method returns false.

Conclusion

Control statements are an essential part of programming in Java. They allow us to control the flow of our program, making it more flexible and easier to debug. By using conditional statements, loop statements, and transfer statements, we can create more complex and powerful programs in Java.