What is Jumping Statements ?
- Jumping statements in Java are used to transfer the control of execution from one part of a program to another part.
Types of Jumping Statements:
- break
- continue
- return
Break :
- Break is used to terminate a loop immediately.
Example:
public class Break {
public static void main(String[] args) {
for(int i=1;i<=5;i++)
{
System.out.println("Iteration no :"+i);
if(i == 3)
{
break;
}
}
}
}
Output:
Iteration no :1
Iteration no :2
Iteration no :3
- The initial value of i is 1.
- When the value of i becomes 3 (i==3) , the if condition is true.
- So , the break statement terminates the loop immediately.
- Therefore , 4 and 5 are not printed.
Continue:
Continue is used to skip the current iteration of the loop and moves to the next iteration.
It does not terminate the entire loop.
Example:
public class Continue {
public static void main(String[] args) {
System.out.println("Continue Statement");
System.out.println();
for(int i=1 ;i<=10;i++)
{
if(i%3 == 0)
{
continue;
}
System.out.println("Iteration no:"+i);
}
}
}
Output:
Continue Statement
Iteration no:1
Iteration no:2
Iteration no:4
Iteration no:5
Iteration no:7
Iteration no:8
Iteration no:10
- The initial value of i is 1.
- The condition is i%3 == 0 , i starts from 1 and ends in 10.
- The condition is true , when the value of i is 3, 6 and 9.
- So, the loop skip the iteration of 3, 6 and 9.
Return :
- Return is used to exit from the method with or without a return value.
Return Without Value:
Example:
public class Return_Without_Value {
public static void main(String[] args) {
System.out.println("Return without a Value");
add(10,20);
}
public static void add(int a, int b)
{
int c=a+b;
System.out.println("Addition of a and b :"+c);
return;
// System.out.println("Completed");
}
}
Output:
Return without a Value
Addition of a and b :30
- Adding a and b, then store the value in c.
- Then printing the statement.
- The return statement terminates the method .
- The statement after return is not printed.
Return with value :
Example:
public class Return_With_Value {
public static void main(String[] args) {
System.out.println("Return with Value");
int output=add(24,82);
System.out.println("Addition of a and b :"+output);
}
public static int add(int a, int b)
{
return a+b;
// System.out.println("Completed");
}
}
Output:
Return with Value
Addition of a and b :106
- add() method is called and performs addition.
- add() method add a and b , then directly return it .
- Storing the returned value in output variable.
- Then printing the output.
Top comments (0)