Java: Break Statement

Profile picture for user arilio666

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