break and continue statement
break:
break statement in java is used to jump out of a loop or switch statement.
Consider the following example:
Example:
for(int i=0; i<10; i++){
if(i==5){
break; //at i=5, condition is true,hence it will take the control out of the loop
}
System.out.print(i + ", ");
}
System.out.println("Out of the loop");
Output: 0, 1, 2, 3, 4, Out of the loop
continue:
if a particular condition is true, then continue will skip statements after it and take the control to the loop again.
Example: Program to print even numbers from 1 to n
int n = 10;
for(int i=1; i<=10; i++) {
if(i%2!=0) {
continue; //takes control again to the loop
}
System.out.print(i + " ");
}
Output: 2 4 6 8 10
continue learning: Loops in Java
Comments
Post a Comment