Java Jump Statements: break, continue, return
1. break Statement
Syntax:
break;
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
System.out.println(i);
Output:
Explanation:
- 'break' stops the loop completely when i == 3.
----------------------------------------
2. continue Statement
Syntax:
continue;
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
System.out.println(i);
Output:
Explanation:
- 'continue' skips the current iteration when i == 3, but the loop continues.
----------------------------------------
3. return Statement
Syntax:
return; // used in void methods
return value; // used in methods returning a value
Example 1 (Void method):
void greet() {
System.out.println("Hello");
return;
Example 2 (Returning a value):
int add(int a, int b) {
return a + b;
Explanation:
- 'return' ends method execution.
- You can use it to return values from a method or just exit a 'void' method.
----------------------------------------
Summary Table:
| Statement | Use Case | Effect |
|-----------|----------------------------------------|-------------------------------|
| break | Exit loop/switch early | Terminates the block |
| continue | Skip one iteration of a loop | Goes to next loop iteration |
| return | Exit method (optionally return value) | Ends method execution |