Â
Jump statements in Java are used to transfer control to another part of the program.Â
The most commonly used jump statements are:
1. break statement: The break statement is used to exit a loop or a switch statement. When a break statement is encountered, the program exits the nearest enclosing loop or switch statement. The break statement can also be used to exit a labeled block. For example:
for (int i = 1; i <= 10; i++) {
Â
if (i == 5) {
Â
break;
Â
}
Â
System.out.println(i);
Â
}
2. continue statement: The continue statement is used to skip the current iteration of a loop and continue with the next iteration. For example:
for (int i = 1; i <= 10; i++) {
Â
if (i % 2 == 0) {
Â
continue;
Â
}
Â
System.out.println(i);
Â
}
3. return statement: The return statement is used to exit a method and return a value (if the method is non-void). For example:
public int add(int a, int b) {
Â
return a + b;
Â
}
4. throw statement: The throw statement is used to throw an exception. An exception is an abnormal event that occurs during the execution of a program. The throw statement can be used to throw a pre-defined exception or a user-defined exception.Â
public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { //throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } }
Post a Comment