Jump Statements in Java | break, continue, return, throw statements

 



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

Post a Comment (0)

Previous Post Next Post