The Wayback Machine - https://web.archive.org/web/20241005070620/https://www.geeksforgeeks.org/usage-of-break-keyword-in-java/
Open In App

Usage of Break keyword in Java

Last Updated : 22 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Break keyword is often used inside loops control structures and switch statements. It is used to terminate loops and switch statements in java. When the break keyword is encountered within a loop, the loop is immediately terminated and the program control goes to the next statement following the loop. When the break keyword is used in a nested loop, only the inner loop will get terminated. Even it is used with if statement to terminated when a certain condition is met.

The break keyword has special usage inside the switch statement. Every case in the switch statement is followed by a break keyword, such that whenever the program control jumps to the next case, it wouldn’t execute subsequent cases. 

Real-life Illustration:

Consider a person climbing stairs. Now the red line here is depicting the stair on which his/her shoe slips and he/she rolls backs to the base. Remember if he/she slips, he/she will always be landing on the base.

Here in computers in programming language there is a keyword called ‘break’ which will abruptly stop the further execution of all the statements following it defined in that scope.

Syntax:

break keyword along with a semicolon

break;

Flow chart of Break statement

Use of Break Keyword is mostly found in loop concepts:

Types of loops  Usage of ‘break’ keyword
Simple loop While the goal of insertion, delete, or updation is completed and there itself wants the program to terminate
Nested loop When the user wants to take command from innermost loop to outer loop 
Infinite loop When the program enters into an infinite looping state 

Case 1: Break keyword inside FOR loop

In order to show how to use the break keyword within For loop. Considering when the value of ‘i’ becomes 39, the break keyword plays its role and terminate the for a loop. All values of ‘i’ before 39, are displayed in the result.

Java




// Java Program to show use of break statement
// inside the For loop
public class GFG {
 
    // Main driver code
    public static void main(String[] args)
    {
        // For loop for iteration
        for (int i = 3; i <= 50; i += 3) {
            if (i == 39) {
                // Using Break keyword to suspend
                // loop when i become 39
                break;
            }
 
            // Printing elements showcasing break usage
            System.out.print(i + " ");
        }
    }
}


Output

3 6 9 12 15 18 21 24 27 30 33 36 

Case 2: Break keyword inside WHILE loop

In order to show how to use the break keyword within the While loop. Considering when the value of ‘i’ becomes 15, the break keyword plays its role and terminate the for a loop. All values of ‘i’ greater than 15 till 35, are displayed in the result.

Java




// Java Program to illustrate the use of break statement
// inside the While loop
 
// Importing generic Classes/Files
import java.util.*;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // While loop for iteration
 
        // Creating and initializing variable
        // outside loop
        int i = 35;
 
        // Condition check
        while (i >= 10) {
            if (i == 15) {
                // Using Break keyword to suspend
                // loop when i become 15
 
                // Decrementing variable initialized above
                i--;
 
                // Break statement
                break;
            }
 
            // Printing elements showcasing break
            System.out.print(i + " ");
            i--;
        }
    }
}


Output

35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 

Case 3: Break keyword inside DO-WHILE loop

In order to show how to use the break keyword within the Do-while loop. Considering when the value of ‘i’ becomes 80, the break keyword plays its role and terminate the for a loop. All values of i” before 80, are displayed in the result.

Java




// Java Program to illustrate the use of break statement
// Inside the do-While loop
 
// Importing all generic classes
import java.util.*;
 
// Importing specific class to take
// user input from the user
import java.util.Scanner;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Using do-While loop
 
        // Creating and initializing a variable
        // over which execution occurs
        int i = 0;
         
        // do loop consisting of executable statements
        do {
            if (i == 80) {
                
                // Incrementing variable by 5
                i += 5;
 
                // Using Break keyword to
                // suspend loop when i become 80
                break;
            }
 
            System.out.print(i + "  ");
            // Printing elements to show break usage
             
            i += 5;
        }
        // Condition check
        while (i <= 100);
    }
}


Output

0  5  10  15  20  25  30  35  40  45  50  55  60  65  70  75  

Case 4: Break keyword inside the Switch statement

In order to show how to use the break keyword within For loop. The break keyword is used at the bottom of every switch case to terminate each statement sequence and prevent the mixing of switch-case statements.

Java




// Java Program to illustrate the use of break statement
// inside the Switch Statement
 
// Importing generic Classes/Files
import java.util.*;
 
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring a variable for switch expression
        int numb = 20;
 
        // Switch expression
        switch (numb) {
 
        // Case statements
        case 10:
            System.out.println("TEN");
 
            // Break keyword to suspend the switch case
            // if given condition is fulfilled
            break;
 
        case 20:
            System.out.println("TWENTY");
            break;
 
        case 30:
            System.out.println("THIRTY");
            break;
 
            // Default case statement
        default:
            System.out.println("INFINITE");
        }
    }
}


Output

TWENTY

Case 5: Break keyword inside label block

In order to show how to use the break keyword within label block. The break keyword is used in the line from where we need to break the label block using break word followed by label name.

Java




/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
    public static void main (String[] args) {
        int i=10;
          GFG:
          {
          // first statement of block GFG
          System.out.println("Block begin");
          // if i==10 then block GFG will stop executing
          if(i==10){
              break GFG;
          }
          // this will not execute if i==10
          System.out.println("Block end");
        }
    }
}


Output

Block begin


Previous Article
Next Article

Similar Reads

Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Break and Continue statement in Java
The break and continue statements are the jump statements that are used to skip some statements inside the loop or terminate the loop immediately without checking the test expression. These statements can be used inside any loops such as for, while, do-while loop. Break: The break statement in java is used to terminate from the loop immediately. Wh
5 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Decision Making in Java (if, if-else, switch, break, continue, jump)
Decision Making in programming is similar to decision-making in real life. In programming also face some situations where we want a certain block of code to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of a program based on certain conditions. These are used to cause t
7 min read
Break statement in Java
Break Statement is a loop control statement that is used to terminate the loop. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Syntax:  break;Basically, break statements are used in situations when we are not sure
3 min read
Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project
Spring AOP has come up with different annotations namely @Before, @After, @Around,@AfterReturning, and @AfterThrowing. Usually, confusions occur among developers were to write the apt code among these annotations. In this article, let us see them by using a sample application. @Around This is the most effective advice among all other advice. The fi
9 min read
Maven Project - LinkedHashMap and LinkedHashSet usage Along with JUnit Testing
In software programming, there are many instances where we need the usage of LinkedHashMap and LinkedHashSet. LinkedHashSet Though HashSet is available, if we need the ordered version of HashSet, we need the LinkedHashSet. The advantage is when we iterate the LinkedHashSet, we get the display of the elements in the inserted order. Because of the ex
7 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
var keyword in Java
The var reserved type name (not a Java keyword) was introduced in Java 10. Type inference is used in var keyword in which it detects automatically the datatype of a variable based on the surrounding context. The below examples explain where var is used and also where you can't use it. 1. We can declare any datatype with the var keyword. Java Code /
4 min read
Super Keyword in Java
The super keyword in Java is a reference variable that is used to refer to parent class when we're working with objects. You need to know the basics of Inheritanceand Polymorphism to understand the Java super keyword.  The Keyword "super" came into the picture with the concept of Inheritance. In this article, we gonna covers all about super in Java
8 min read
Protected Keyword in Java with Examples
Access modifiers in Java help to restrict the scope of a class, constructor, variable, method, or data member. There are four types of access modifiers available in java. The access of various modifiers can be seen in the following table below as follows:  The protected keyword in Java refers to one of its access modifiers. The methods or data memb
5 min read
volatile Keyword in Java
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem. Consider the below example. class SharedObj { // Changes made to sharedVar in one thread // may not immediately reflect in other th
5 min read
transient keyword in Java
transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type. transient keyword plays an impo
3 min read
instanceof Keyword in Java
In Java, instanceof is a keyword used for checking if a reference variable contains a given type of object reference or not. Following is a Java program to show different behaviors of instanceof. Henceforth it is known as a comparison operator where the instance is getting compared to type returning boolean true or false as in Java we do not have 0
4 min read
return keyword in Java
In Java, return is a reserved keyword i.e., we can't use it as an identifier. It is used to exit from a method, with or without a value. Usage of return keyword as there exist two ways as listed below as follows:  Case 1: Methods returning a valueCase 2: Methods not returning a valueLet us illustrate by directly implementing them as follows: Case 1
6 min read
strictfp keyword in java
In Java, the strictfp is a modifier that stands for strict floating-point which was not introduced in the base version of Java as it was introduced in Java version 1.2. It is used in Java for restricting floating-point calculations and ensuring the same result on every platform while performing operations in the floating-point variable. Floating-po
2 min read
abstract keyword in java
In Java, abstract is a non-access modifier in java applicable for classes, and methods but not variables. It is used to achieve abstraction which is one of the pillars of Object Oriented Programming(OOP). Following are different contexts where abstract can be used in Java. Characteristics of Java Abstract KeywordIn Java, the abstract keyword is use
7 min read
Native Keyword in Java
The native keyword in Java is applied to a method to indicate that the method is implemented in native code using JNI (Java Native Interface). The native keyword is a modifier that is applicable only for methods, and we can’t apply it anywhere else. The methods which are implemented in C, C++ are called native methods or foreign methods. The native
4 min read
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class. It is used to restrict a user in Java. The following are different contexts where the final is used: VariableMethodClass The final keyword is used to define constants or prevent inheritance in Java. To understand how and when to use final
12 min read
static Keyword in Java
The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class rather than an instance of the class. The static keyword is used f
9 min read
Can String be considered as a Keyword?
Is string a keyword? A string is NOT a keyword. It is one of the names of data types declared in the standard library. How to check if a string is a keyword in C++? In C++ there is no special method to check whether the given string is a keyword or not. But there are a set of keywords present which is listed below-"auto", "break", "case", "char", "
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Article Tags :
Practice Tags :