Jump statement in Java

Jump Statement in Java ?



  • It can be used to transfer the control from one point to another point within the program.
  • Mainly there are three jump statements in java.

  1. break statement
  2. continue statement
  3. return statement
break statement

  • It can be used to come out of the body of loop.
  • In other words we can say that, it terminates the current loop.
  • break statement are commonly used with loop and switch statement.(for,while,do while).

Example 1:Program without break

 class Easy  
 {   
  public static void main(String[] args)   
  {  
  for(int i=1;i<=10;i++)  
  {  
  System.out.print(i+" ");  
  }  
  }  
 }
 
 /*  
 ### OUTPUT ###  
 1 2 3 4 5 6 7 8 9 10  
 */  


Example 2:Same Program with break

 class Easy  
 {   
  public static void main(String[] args)   
  {  
  for(int i=1;i<=10;i++)  
  {  
  System.out.print(i+" ");  
  if(i==5)//terminate the loop when i=5  
   break;  
  }  
  }  
 }  
 
 /*  
 ### OUTPUT ###  
 1 2 3 4 5  
 */  


continue statement

  • It can be used to skip the next statement and continue the loop.
  • continue statement are commonly used with loop(for,while,do while).

Example 1:

 class Easy  
 {   
  public static void main(String[] args)   
  {  
  for(int i=1;i<=5;i++)  
  {  
   if(i==3)//skip the next statement when i=3  
   continue;  
   else  
   System.out.print(i+" ");  
  }  
  }  
 }
 
 /*  
 ### OUTPUT ###  
 1 2 4 5  
 */  


Example 2:

 class Easy  
 {   
  public static void main(String[] args)   
  {  
  for(int i=1;i<=5;i++)  
  {  
   if(i>=3)//skip the next statement when i>=3  
   continue;  
   else  
   System.out.print(i+" ");  
  }  
  }  
 }  
 /*  
 ### OUTPUT ###  
 1 2   
 */  


Example 3:

 class Easy  
 {   
  public static void main(String[] args)   
  {  
  for(int i=1;i<=5;i++)  
  {  
   if(i<=3)//skip the next statement when i<=3  
   continue;  
   else  
   System.out.print(i+" ");  
  }  
  }  
 }  
 
 /*  
 ### OUTPUT ###  
 4 5  
 */  


Example 4:

 class Easy  
 {   
  public static void main(String[] args)   
  {  
  for(int i=1;i<=5;i++)  
  {  
   if(i!=3)//skip the next statement when i!=3  
   continue;  
   else  
   System.out.print(i+" ");  
  }  
  }  
 }
 
 /*  
 ### OUTPUT ###  
 3  
 */  


return statement

  • return statement used to terminate the current function and transfer the control to the calling function.
  • we can also use return statement to trasfer value from one function to another.
Example-1
 class Easy  
 {   
   int add()  
   {  
   int x=10,y=30;  
   return (x+y);//returning x+y=40  
   }  
  public static void main(String[] args)   
  {  
  Easy obj=new Easy();  
  int rs=obj.add();//passing returning value to rs  
  System.out.println("Add="+rs);  
  }  
 }
 
 /*  
 ### OUTPUT ###  
 Add=40  
 */  


Hope This is useful for you. Visit our channel for job updates- Youtube

Post a Comment

0 Comments