Table of contents
1.
Introduction
2.
What is the Break Statement in Java?
2.1.
Code
2.2.
Java
3.
How break statement works?
3.1.
Java
4.
Flowchart of Break Statement in Java
5.
Examples of Break statement
5.1.
Break Statement within a for loop
5.2.
Implementation
5.3.
Java
5.3.1.
Output
5.4.
Break Statement within a While Loop
5.5.
Implementation
5.6.
Java
5.6.1.
Output
5.7.
Break Statement within a Do While Loop
5.8.
Implementation
5.9.
Java
5.9.1.
Output
5.10.
Break Statement in a Nested Loop
5.11.
Implementation
5.12.
Java
5.12.1.
Output
5.13.
Labelled Break Statement in Java
5.14.
Implementation
5.15.
Java
5.15.1.
Output
5.16.
Break Statement in Switch Cases
5.17.
Implementation
5.18.
Java
5.18.1.
Output
6.
Frequently Asked Questions
6.1.
What is a break and continue statement?
6.2.
What is break and continue in Java?
6.3.
How to break a do-while loop?
7.
Conclusion
Last Updated: Nov 16, 2024
Easy

Break Statement in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ever found yourself needing to exit a loop before its natural completion? Java's break statement is your go-to solution. This powerful control flow statement allows developers to gracefully terminate loops and switch statements, making code more efficient and readable. Whether you're iterating through an array, searching for a specific value, or implementing complex control structures, understanding the break statement is essential for writing clean and effective Java code. In this blog, we'll explore how the break statement works, when to use it, and best practices for implementing it in your programs.

Break Statement in Java

What is the Break Statement in Java?

In Java, the Break Statement is used to terminate a loop or a switch statement. When a compiler encounters a break statement, it terminates the loop immediately and moves to the block of code that is present just after the loop.

The code below shows how we use Break Statement in Java.

Code

  • Java

Java

class Solution {
  public static void main(String[] args) {
     // Let's see how break statement works
     int start = 0;
     while(true) {
         // our bound is 10
         // so there is no point to increment start further more, otherwise this loop will works as an infinite loop
         // so we will break out of the loop using break statement
         if(start > 10) {
             // this is a syntax of break statement
             break;
         }
         start ++;
     }
  }
}
You can also try this code with Online Java Compiler
Run Code

Also reads - Jump statement in java

How break statement works?

In Java, the break statement is used to terminate the execution of a loop, switch statement, or labeled block. When encountered, break immediately exits the innermost enclosing loop or switch, transferring control to the statement immediately following the terminated construct. It helps control the flow of execution and exit loops or switches prematurely based on certain conditions. Here's a brief example:

  • Java

Java

class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
// Break out of the loop when i equals 3
break;
}
System.out.println("Value of i: " + i);
}
System.out.println("Loop terminated.");
}
}
You can also try this code with Online Java Compiler
Run Code

Output

output

In this example, the loop will print values of i from 1 to 2 and then terminate when i equals 3 due to the break statement. The "Loop terminated." statement will be printed after the loop exits.

Flowchart of Break Statement in Java

flowchart of break statement in java

Examples of Break statement

Break Statement within a for loop

Implementation

  • Java

Java

class Solution {
  public static void main(String[] args) {
     // print the last number between 100 to 200 which is a perfect square
     int last_square = 0;
     for(int number = 200; number >= 100; number --) {
         int root = (int) Math.sqrt(number);
         if(root * root == number) {
             last_square = number;
             break;
         }
     }
     System.out.println(last_square);
     return;
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

196


The code above finds the last perfect square number between 100 and 200. So we are iterating from the end and checking whether the multiplication of a root of a number with itself is equal to that number. If, at any point, this condition is satisfied, we will break the loop because the last digit from the start is equivalent to the first number from the end. So that's how the break statement works inside the For Loop.

Break Statement within a While Loop

Implementation

  • Java

Java

class Solution {
  public static void main(String[] args) {
      // You are given a string. You have to print the first character whose occurrence is more than 2
      String mystring = "codingninjas";
      int[] frequency = new int[26];
      // initialize the array
      for(int index = 0; index < 26; index ++) {
          frequency[index] = 0;
      }
      int index = 0, length = mystring.length();
      boolean found = false;
      while(index < length) {
          // get the current character
          Character cur_char = mystring.charAt(index);
          // get its hash value
          int hash = (int) (cur_char - 'a');
          frequency[hash] ++;
          if(frequency[hash] > 2) {
              System.out.println(cur_char);
              found = true;
              break;
          }
          index ++;
      }
      // there is no character whose count is greater than 2
      if(found == false) {
          System.out.println("There is no such character");
      }
      return;
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

n


The code above is finding the first character whose occurrence is greater than two. Here we use a frequency array to store the count of each character. We are iterating from the start of the string. We find every character's hash value by subtracting the ASCII value of ‘a’ from the current character and incrementing the value corresponding to that hash in the frequency array. After that, we check whether that incremented value is greater than two. If the condition satisfies, then we will break the loop. Otherwise, the loop keeps repeating itself until it iterates the whole string.

Break Statement within a Do While Loop

Implementation

  • Java

Java

class Solution {
  public static void main(String[] args) {
      // print the cube of the numbers from 1 to 10
      int number = 1;
      do {
          int cube = number * number * number;
          System.out.print(cube);
          System.out.print(" ");
          number ++;
          if(number > 10) {
              break;
          }
      } while(true);
      return;
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

1 8 27 64 125 216 343 512 729 1000


The code above prints a cube of the numbers from one to ten. We have initialized the variable with one and are checking whether the number is greater than ten. When the condition satisfies, we will break the loop. Otherwise, the loop will keep repeating itself.

Break Statement in a Nested Loop

Implementation

  • Java

Java

class Solution {
  public static void main(String[] args) {
      // find the sum of first n natural numbers for every n from 1 to 10
      for(int n = 1; n <= 10; n ++) {
          int number = 1, sum = 0;
          while(true) {
              if(number > n) {
                  // number has exceeded the boundary
                  break;
              }
              sum += number;
              number ++;
          }
          System.out.print(sum + " ");
      }
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

1 3 6 10 15 21 28 36 45 55


The code above finds the sum of the first ‘n’ natural numbers for every ‘n’  from one to ten. The first loop is for iterating an every ‘n’ from one to ten, and the inner loop is for finding the sum. We have initialized the number with one and are repeating the process until our number becomes greater than the current  ‘n’. Here the break statement is breaking the inner loop, not the outer loop because it can only break the block in which it is present.

Labelled Break Statement in Java

Implementation

  • Java

Java

class Solution {

  public static int SumOfDigits(int num) {
      int cur = 0;
      while(num > 0) {
          cur += (num % 10);
          num /= 10;
      }
      return cur;
  }

  public static void main(String[] args) {
      // print the sum of digits of number from 10 to 20
      int number = 10;
      mylabel:
      while(true) {
          if(number > 20) {
              break mylabel;
          }
          System.out.print(SumOfDigits(number));
          System.out.print(" ");
          number ++;
      }
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

1 2 3 4 5 6 7 8 9 10 2


The code above prints the sum of digits of numbers from ten to twenty. We have initialized the number with ten and keep iterating over the loop until our number exceeds twenty. When the number becomes twenty-one, we will break the code block inside the label, which means we will get out of the loop.

Break Statement in Switch Cases

Implementation

  • Java

Java

class Solution {
  public static void main(String[] args) {
      // print the lexicographic position of the string "bca"
      String mystring = "bca";
      switch(mystring) {
          case "abc":
              System.out.println(1);
              break;
          case "acb":
              System.out.println(2);
              break;
          case "bac":
              System.out.println(3);
              break;
          case "bca":
              System.out.println(4);
              break;
          case "cab":
              System.out.println(5);
              break;
          case "cba":
              System.out.println(6);
              break;
          default:
              break;
      }
  }
}
You can also try this code with Online Java Compiler
Run Code

Output

4


The code given above calculates a lexicographic position of a given string. When our given string gets matched with the case of the switch statement, it will break the switch statement. At last, we get our desired output.

Frequently Asked Questions

What is a break and continue statement?

The break statement exits a loop entirely, while the continue statement skips the current iteration and moves to the next one.

What is break and continue in Java?

In Java, break terminates a loop or switch block, and continue skips the remaining code in the current iteration of a loop.

How to break a do-while loop?

Use the break statement within the loop body to exit a do-while loop based on a specific condition.

Conclusion

In this article you’ve learned the Break Statement and the different implementations of the Break Statement in Java, along with its Flowchart.

We hope this blog has helped you enhance your knowledge of Break Statement in Java.

You can refer to Loops in Java and Jump Statements in Java for more details about this topic.

Head over to our practice platform Code360 to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Live masterclass