Transfer Statement
- break;
- continue;
- label
Break-:The break statement in java is used to terminate from the loop, switch and labeled block immediately. When a break statement is encountered inside a loop, the loop iteration stops there, and control returns from the loop immediately to the first statement after the loop. Basically, break statements are used in situations when we are not sure about the actual number of iterations for the loop, or we want to terminate the loop based on some condition.
we can use break statements in the following places.
- inside switch to stop fallthrough.
example-:
int x=0;
switch(x){
case 0:
System.out.print("hello");
case 1:
break;
case 2:
System.out.print("Hi");
default:
System.out.print("default");
}
output -: case 0,1 both excute.
- inside loops to break loop execution based on some condition .
example-:
for(int i=0;i<10;i++){
if(i==5)
break;
System.out.print(i);
}
output-: 0 1 2 3 4
- inside labeled blocks to break block execution based on some condition.
example-:
class Test{
public static void main(String... args){
int x=10;
l1:
{
System.out.print("Begin");
if(x==10)
break l1;
System.out.print("end");
}
System.out.print("Hello");
}
output-: Begin Hello
- these are the only places where we can use break statements if we are using any where else we will get compile time error saying break outside switch and loop.
Continue Statement
Continue-: we can use continue statements inside a loop to skip the current iteration and continue for next iteration.
example-:
for(int i=0;i<10;i++){
if(i%2==0)
continue;
System.out.print(i);
}
output-> 1 3 5 7 9
- we can use continue statements in loops if we are using them anywhere else we will get compile time error saying continue the outside loop.
example-:
class Test{
public static void main(String... args){
int i=10;
if(i==10)
continue;
System.out.print("Hello");
}
}//compile time error saying continue the outside loop
labeled break & continue
we can use labeled break & continue to break and continue the particular loop in nested loops.
example-:
l1:
for(----------------------------){
l2:
for(-----------------------------){
for(---------------------------------------------){
break l1;
break l2;
}
}
}
examples-:
/*
case 1-:
l1:
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(i==j)
break;
System.out.println(i + " "+j);
}
}
output-:
1 0
2 0
2 1
case 2-:
l1:
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(i==j)
break l1;
System.out.println(i + " "+j);
}
}
output-: no output
case 3-:
l1:
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(i==j)
continue;
System.out.println(i + " "+j);
}
}
output-:
0 1
0 2
1 0
1 2
2 0
2 1
case 4-:
l1:
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(i==j)
continue l1;
System.out.println(i + " "+j);
}
}
output-:
1 0
2 0
2 1
*/
do-while & continue
example-:
int x=0;
do{
x++;
System.out.print(x);
if(++x<5)
continue;
x++;
System.out.print(x);
}while(++x<10);
output-: 1 4 6 8 10