What is the break statement in Java?

Overview

The break statement in Java is used to exit the program from a loop. After a break statement is called, control is returned from the loop to the next statement outside the loop. break statements are used in scenarios where we need to exit the loop on a specific condition, or when the number of iterations is uncertain.

Syntax

break;
Use of "break" statements in loops to make different decisions

Code example

class BreakExample {
public static void main(String args[])
{
int i=0;
// Initially decrementing loop is set to run from 9 to 1
for ( i = 9; i>=1; i--) {
// terminate loop when remainder is 0
if ((i%5)==0)
break;
System.out.println("iteration number: " + i);
}
System.out.println("Loop completed.");
System.out.println("Last iteration number" +i);
}
}

Code explanation

  • Lines 6–12: We create a decrementing loop to check if each i-th number’s modulus is zero. In the case that it is zero, the loop is exited.
  • Lines 13–14: We are outside the loop. We print the message of the loop termination, along with the latest iteration number.

Free Resources