break Statement

Break is one of the control statement available in java. It can break control of execution. It has two version labeled and unlabeled. Most of the usage of break statement you have seen is unlabeled. break statement is used to jump out of the loop.

Break statement also used in switch statement, that one is unlabelled break statement.


Unlabelled break

Example :


// file: brk.java
// www.jgyan.com

class brk
{
public static void main(String ...arg)
{
int i;
for(i=0;i<100;i++)
{
if( i==30)
break;
else
System.out.println(i);
}

}
}


In above program, when i is equal to 30, control will jump out of for loop. Unlabelled break is used to jump control out of one loop or single case in switch. We can't jump out of multiple loop using unlabelled break.


Labelled break

In labelled break we specify one label and at the time of using break we specify name of label as well where we want to transfer control of execution.


Example :


// file : brk1.java
// www.jgyan.com
class brk1
{
public static void main(String ...arg)
{
boolean flag=false;
int i,j;
int data[][]={{2,3,6,7},{23,34,5,3}};
search:
for(i=0;i<2;i++)
for(j=0;j<4;j++)
{
if( i==34)
{
flag=true;
break search;
}
}
if(flag)
System.out.println("Number is found");
else
System.out.println("Number is not found");
}
}
/* Output
Number is not found
*/

Labelled break won't transfer control of execution to label(search in our case). It simply specify that statement appearing after labelled statement, will get executed. In our program for loop having search label. 'break search;' statement execute statement immediately after for loop, which is 'if' statement.