Break Statement in Java

Break is mainly used to exit a loop. Inside a loop, when the JVM encounters a break statement, it breaks the loop and passes the control to the next statement after the loop.

This statement is mainly useful when we need to exit from an infinite loop or exit for a loop on specific condition meet.

Example:

public class BreakDemo {

	public static void main(String[] args) {

		int i = 0;
		while(true){
			i++;
			System.out.print(i+" ");
			if(i==10)
				break;
		}
	}
}
Try It

In the above program, while(true) is an infinite loop. But, we need to print from values 1 to 10. So, when the loop encounters i==10, break comes into action and the loop breaks.

The output is: 1 2 3 4 5 6 7 8 9 10


Next > < Prev
Scroll to Top