Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is the Break Statement in Java?
2.1.
Code
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 the difference between Continue and Break Statements in Java?
6.2.
How is the Labelled Break Statement different from Regular Break Statement? 
6.3.
How do break statements optimize the program?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Break Statement in Java

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Hello Ninja, I hope you are doing great. Do you know about Break Statement in Java? If not, don't worry. We are here to enrich your knowledge and clear all your doubts.

Break Statement in Java

This article will discuss the Break Statement in Java and its Flowchart. We will also discuss the different ways to implement Break Statement in Java along with their codes and outputs.

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

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 ++;
      }
   }
}

Also reads - Jump statement in java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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.");
}
}

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;
  }
}

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;
  }
}

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;
  }
}

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 + " ");
      }
  }
}

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 ++;
      }
  }
}

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;
      }
  }
}

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 the difference between Continue and Break Statements in Java?

The Break Statement terminates the loop and transfers the control immediately to the statement just after the loop, whereas the Continue Statement skips the current iteration and proceeds with the next iteration.

How is the Labelled Break Statement different from Regular Break Statement? 

The Labelled Break Statement breaks out of the nested loops by specifying a label for the outer loop whereas the Regular Break Statement can only break out of the nested loops.

How do break statements optimize the program?

The break statements can be used to skip unnecessary iterations. This can save the processing time and the overall performance of the program. So it is essential to use the break statement when we are sure we don't need to iterate more.

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 Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Happy Learning Ninja!

Previous article
Jump Statements in Java
Next article
Iterable Interface in Java
Live masterclass