What are Jump statements?
Jump statements are used to transfer control to another part of the program.
1. break Statement: Exits the current loop or switch statement.
Example : break Statement #
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i is 3
}
System.out.println("i = " + i);
}
}
}
Output:
i = 1
i = 2
The loop terminates when i equals 3 due to the break statement.
2. continue Statement: Skips the remaining code in the current iteration of a loop and proceeds with the next iteration.
Example : continue Statement #
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the rest of the loop iteration when i is 3
}
System.out.println("i = " + i);
}
}
}
Output:
i = 1
i = 2
i = 4
i = 5
The loop skips the iteration when i equals 3 due to the continue statement.
3. return Statement: Exits from the current method and optionally returns a value.
Example : return Statement #
public class ReturnExample {
public static void main(String[] args) {
System.out.println("The sum is " + sum(10, 20));
}
public static int sum(int a, int b) {
return a + b; // Return the sum of a and b
}
}
Output:
The sum is 30
The return statement exits the sum method and returns the sum to the caller.