C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

break statement in java with example

In this java tutorial, we are going to learn about 'break' statement. How and when a break statement is used, we will learn using example here?
Submitted by IncludeHelp, on November 29, 2017

break statement is used to break the execution of any loop or to break (come out from particular case body) the switch cases in switch statement.

break statement interrupts the flow of loop at certain conditions, in case of multiple loops, break statement only break that loop in which break is used.

Syntax of break statement

break;

The syntax is a simple break keyword, used within the loop body or after the switch case statements.

Let’s understand with this flow chart:

break statement in java

Image reference: https://www.programiz.com/c-programming/c-break-continue-statement

Example of break statement

public class breakstate {
	public static void main(String arg[]){
		int i;
		for(i=1;i<=12;i++){
			if(i==8){
				break;
			}
			System.out.println(i);
			}
		}
}

Output

    1
    2
    3
    4
    5
    6
    7

In this program, the loop is running from 1 to 12 and we are using break inside the if condition (i==8). So, when value of i will be 8, loop execution will be stopped and program’s execution will jump to the next statement written just after the loop body.









COMMENTS