Font Awesome Icons

Tutorial

Java break statement

The Java break keyword is used to terminate for, while, or do-while loop. It may also be used to terminate a switch statement as well.Whenever a break statement is encountered inside a loop, the control directly comes out of loop and the loop gets terminated for rest of the iterations.
When a break statement is used inside a nested loop, then only the inner loop gets terminated.“break” word followed by semi colon.

Syntax:

for(…)
{
//loop statements

break;
}

Use of break in a while loop

class B1 {
public static void main(String args[]){
int a =0;
while(a<=100)
{
System.out.println(“Value of variable is: “+a);
if (a==2)
{
break;
}
a++;
}
System.out.println(“Out of while-loop”);
}
}

Note:In this the loop will run from 0 to 100, but since we have a break statement that only occurs when the loop value reaches 2, the loop gets terminated and the control gets passed to the next statement in program.

Use of break in a for loop

class B2 {
public static void main(String args[]){
int a;
for (a =100; a>=10; a –)
{
System.out.println(“value: “+a);
if (a==99)
{
break;
}
}
System.out.println(“Out of for-loop”);
}

 

}

 

Note:In this the loop will run from 0 to 100, but since we have a break statement that only occurs when the loop value reaches 99, the loop gets terminated and the control gets passed to the next statement in program.

Labeled break statement

We can use break statement with a label.Here, we write a label name after a break statement.

 class B3 {
public static void main(String[] args) {
gkp:
for(int i=1;i<=4;i++){
lko:
for(int j=1;j<=4;j++){
if(i==2&&j==2){

break gkp;
}
System.out.println(i+” “+j);
}
}
}
}

Hi, Welcome to etechvidya