Break:
Break is a transfer statement which can be used either inside switch statement or inside a loop.
- The break statement, when used in switch will transfer the control from inside the switch to outside the switch, so that we skip the execution of removing cases.
- The break statement, when used in loop, will transfer the control from inside the loop to outside the loop, so that we will skip the execution of remaining iterations.
Note: When we are specifying the break statement in a loop we are recommended to specify the break statement along with condition.
Program:
class BreakDemo{
public static void main(string[] args){
int sum=0, capacity=15;
for(int i=1, i<=100; i++){
System.out.println(i);
sum=sum+i;
if(sum>=capacity)
break;
}
System.out.print.ln(sum);
}
}
Continue:
continue is a transfer statement which has to be used only in loops. The continue statements will skip the current iteration and continues with the remaining iterations.
Note:
When we are specifying a continue statement in a loop, then we are recommended to specify the continue statement along with a condition.
Program:
class ContinueDemo{
public static void main(string[] args){
for(int i=1, i<=20; i++){
if(i==7|i==13)
continue;
System.out.print.ln(i);
}
}
}