Skip to main content

Java: Break Statement

In the Java programming language, there is a break statement that is used in almost every loop and switch statement. Normally a break is used to cut the connection of a loop or cut the ongoing loop and continue to the next part of the code.

We must use the break statement when using the looping concept and it is vital because the loop will run endlessly if you run the code without break.

Syntax

break;

Example

import java.util.ArrayList;

public class Test
{
    public static void main(String[] args)
    {
        for(int number = 0; number < 100; number++)
        {
            if(number == 12)
            {
                break;
            }
            System.out.println("Match:" +number);
        }
    }
}

Output:

Match:0
Match:1
Match:2
Match:3
Match:4
Match:5
Match:6
Match:7
Match:8
Match:9
Match:10
Match:11
  • Here I have used a normal break statement where I have initiated number should be less than 100 and given the condition only that number should be equal to 12.
  • When 12 is reached it should break and come out of the loop.
  • Thus break is an efficient statement to get rid of the loop and continue to the rest of the code.
Tags
Submitted by arilio666 on November 2, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.