Break Statement in Java

The break statement can only be used within switch, for, while, and do-while statements. Breaking out of a for, while or do-while loop can be done using the break statement, but it must be controlled by an exit condition; otherwise, no step is executed.

Syntax

break;

Example

public class BreakExample {

public static void main(String[] args) {

//using for loop

for(int x=1;x<=10;x++){

if(x==5){

//using for loop

break;

}

System.out.println(x);

}

}

}

Output

1

2

3

4

5

6

Example of Break statement in while loop

public class BreakWhileExample {

public static void main(String[] args) {

//while loop

int x=1;

while(x<=10){

if(x==7){

//using break statement

x++;

break; //it will break the loop

}

}

}

Output

1

2

3

4

5

6

Example of Break statement in do-while loop

public class BreakDoWhileExample {

public static void main(String[] args) {

//declaring variable

int x=1;

//do-while loop

do{

if(x==5){

//using break statement

x++;

break; //it will break the loop

}

System.out.println(i);

x++;

}while(x<=10);

}

}

Output

1

2

3

4

5

6

Example of Break statement in switch-case

public class ForExample {

public static void main(String args[]){

int num=2;

switch (num)

{

case 1:

System.out.println(“Case 1 “);

break;

case 2:

System.out.println(“Case 2 “);

break;

case 3:

System.out.println(“Case 3 “);

break;

default:

System.out.println(“Default “);

}

}

}

Output

Case 2

Copyright 1999- Ducat Creative, All rights reserved.