Java Break Statement with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

The break statement is a vital control flow statement in Java that terminates the execution of loops or switch statements prematurely. In this article, we will learn about the break statement in detail through examples—its syntax, usage in different contexts, complexity analysis, and more.

The break statement allows you to exit from a code block, such as a loop or a switch statement. When encountered inside one of these blocks, the break statement immediately terminates the current iteration and transfers control to the following statement following the block.

The essential purposes served by the break statement are:

  • Terminating loops prematurely before their average completion.
  • Branching out of conditional blocks in switch statements.

The syntax of the break statement is simple – a semicolon follows the break keyword:

break;

Let’s look at some common scenarios where the break statement is used in Java programs.

break statement in java example

Uses of the Break Statement in Java

1) Terminating a Switch Case

The break statement is commonly used to terminate a particular case in a switch statement. Without a break statement, control flow would “fall through” to subsequent cases until a break or the end of the switch block is reached.

Here is an example demonstrating the use of break-in switch cases:

public class DayOfWeek {
    public static void main(String[] args) {
        int day = 3;

        switch (day) {
            case 1:
                System.out.println("Monday");
                break; // Terminates this case

            case 2:
                System.out.println("Tuesday");
                break;

            case 3:
                System.out.println("Wednesday");
                break;

            default:
                System.out.println("Invalid day!");
        }
    }
}

Output:
Wednesday

After printing the day, the break statements ensure that only that case is executed before jumping out of the switch block.

2) Exiting a Loop Prematurely

The break statement is commonly used to terminate loop execution based on some condition. This allows the loop to exit prematurely before its normal completion.

Here is an example to demo using a break to exit a while loop:

public class WhileLoopExample {
    public static void main(String[] args) {
        int i = 1;
        while (true) {
            if (i > 3) {
                break;
            }
            System.out.println(i);
            i++;
        }
    }
}

Output:
1
2
3

The break statement is used to exit the while loop when the value of i becomes greater than 3.

One important point is that when nested loops are present, a break statement only terminates the innermost loop containing it.

exiting-a-loop-prematurely

3) Using Break as a Form of Goto

Unlike languages like C, Java does not have an explicit goto statement. The break statement is sometimes used to simulate goto behavior in Java by “jumping out” of labeled blocks.

Labeling Blocks: We can label any block of code by prefixing it with an identifier followed by a colon:

block_label: {
  // Code statements
}

For example:

int[][] arr = {
  {1, 2, 3}, 
  {4, 5, 6}  
};

int sum = 0;

row_loop: 
for(int i=0; i<arr.length; i++) {
  for(int j=0; j<arr[i].length; j++) {
    if(arr[i][j] % 2 != 0) {
      continue row_loop; 
    }
    sum += arr[i][j];
  }
}

System.out.println("Sum of even elements = " + sum);

Output:
// Sum of even elements = 12

Here row_loop is the label for the outer for loop.

Breaking to a Label: To exit the labeled block, we can use the break statement with a label name.

For example:

block_label: {
  // Some code
  
  if(some_condition) {
    break block_label;
  }
  
  // Rest of code
}

When the break with the label is encountered, the control jumps just after the labeled block.

Let’s add a break with label to the multi-dimensional array example:

public class MultiDimensionalArrayExample {
    public static void main(String[] args) {
        int[][] multiArray = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        int targetValue = 5;
        boolean found = false;


        searchLoop: // Label for the outer loop
        for (int i = 0; i < multiArray.length; i++) {
            for (int j = 0; j < multiArray[i].length; j++) {
                if (multiArray[i][j] == targetValue) {
                    found = true;
                    break searchLoop; // Breaks out of both loops
                }
            }
        }


        if (found) {
            System.out.println("Value " + targetValue + " found in the multi-dimensional array.");
        } else {
            System.out.println("Value " + targetValue + " not found in the multi-dimensional array.");
        }
    }
}

Output:
Value 5 is found in the multi-dimensional array.

The break statement with the searchLoop label terminates the outer for loop’s execution when an odd element is encountered in the array.

A key point to note is that labels have function scope in Java. We cannot jump out of a function using a label defined outside it.

Complexity Analysis

  • Time Complexity: The break statement runs in constant O(1) time. Any overhead depends on where it is used.
  • Space Complexity: The break statement does not require additional memory, so it takes constant O(1) auxiliary space.

Conclusion

In conclusion, the break statement in Java plays a crucial role in controlling the execution flow in loops and switch statements.

This article thoroughly explored its syntax and usage in various contexts. It demonstrated how the break statement could terminate specific cases in switch statements, premature exit loops based on conditions, and even simulate a form of “goto” behaviour using labelled blocks.

The article also briefly touched upon the complexity analysis of the break statement, emphasizing its low time and space complexities. In Java, the break statement proves to be an essential tool for programmers to efficiently manage the flow of their code, ensuring that it behaves as desired in different scenarios.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

Leave a Reply

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