Jump Statement in Java ?
Jump Statement in Java ?
- It is used to transfer the control from one point to another point in the program.
- There are three jump statements are used in java.
- break statement
- continue statement
- return statement
break statement
- It is used to transfer the control out of the body of loop.
- In other word we can say that it terminates the current loop.
- break statement are mostly used with loop(for,while,do while) and switch statement.
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 */
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 is used to skip the next statement and continue the loop.
- continue statement are mostly used with loop(for,while,do while).
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 */
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 */
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 */
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 terminates 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.
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 */