Previous | Home | Next |
break is a keyword which is used to terminate a switch or a loop, break is used to exit the loop.It is a compile error to use break anywhere else.'break' breaks the loop without executing the rest of the statements in the block.
Example :
if(i==9) break; // loop terminates over here Example for ( int i=1 ; i<=5 ;i++) { if(i==3) break; System.out.print(i); } System.out.print("Hello");
output :
1 2 Hello
The break statement can be followed by a label. label is the name that identifies a block of code. When this form of break executes, control is transferred out of the named block of code. To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon.
Example :
class LabeledBreak { public static void main(String args[]) { outer: for(int i=1;i<=5;i++) { inner: for(int j=1;j<=5;j++) { if(j>i) break outer; System.out.print(j); } System.out.println(); } } }
output :
1
Previous | Home | Next |