3. Jump Statements or Break and Continue statement
The break statement is used to immediately exit from a loop, that is stopping the loop execution.
The continue statement is used to skip the current iteration of a loop and move to the next iteration.
break statement:
Example:
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
if (number == 30) {
break;
}
System.out.println("Number: " + number);
}
}
}
output:
Number: 10
Number: 20
- In this example, the break statement stops the loop immediately when the value becomes 30.
- As soon as number == 30 is true, the loop ends and no further elements are printed.
continue statement:
Example:
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
if (number == 30) {
continue;
}
System.out.println("Number: " + number);
}
}
}
output:
Number: 10
Number: 20
Number: 40
Number: 50
- In this example, the continue statement skips the current iteration when the value is 30.
- As a result, 30 is not printed and the loop moves directly to the next element.
See you in next page....🙂