JUMP STATEMENTS IN JAVA
- In Java, jump statements are used to alter the
flow of control in a program, allowing it to skip
certain code blocks or repeat code based on
specific conditions.
- Java has three main jump statements:
1) break:
- The break statement is used to terminate the
execution of a loop or a switch statement
prematurely.
- When the break statement is encountered
within a loop or switch, the program
immediately exits that loop or switch and
continues with the next statement after it.
- It is commonly used when a specific condition
is met, and there is no need to continue the loop
or switch execution.
- Ex: for (int i = 1; i <= 5; i++)
{
if (i == 3)
Topic: Jump Statements Prepared by Ashwini Y.
{
break; // exit the loop when i is 3
}
System.out.print(i + " "); //Output: 1 2
}
What will happen if:
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
break;
System.out.println(i+ " ");
}
}
System.out.println("Hello!!!");
2) continue:
- The continue statement is used to skip the
remaining code within a loop iteration and
Topic: Jump Statements Prepared by Ashwini Y.
move on to the next iteration of the loop.
- When the continue statement is encountered
within a loop, the remaining statements within
that loop iteration are skipped, and the loop
proceeds with the next iteration.
- It is useful when you want to skip certain
iterations of the loop based on specific
conditions.
- Ex: for (int j = 1; j <= 5; j++)
{
if (j == 3)
{
continue; // skip the iteration when j is 3
}
System.out.print(j + " "); //Output: 1 2 4 5
}
Combination of continue and break:
public class BreakContinueExample
{
public static void main(String[] args)
{
Topic: Jump Statements Prepared by Ashwini Y.
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
continue;
}
System.out.println("Current value: " + i);
if (i == 4)
{
break;
}
}
System.out.println("Loop ended");
}
}
/*Current value: 1
Current value: 2
Current value: 4
Loop ended */
Topic: Jump Statements Prepared by Ashwini Y.
3) return:
- The return statement is used to exit a method
prematurely and return a value
(if the method has a return type).
- When the return statement is encountered
within a method, the method execution stops,
and the specified value is returned to the caller.
- It is commonly used to terminate a method's
execution and provide the result of the method
to the calling code.
- Ex: public static int addNumbers(int a, int b)
{
return a + b; // return the sum of a and b
}
************************************************************
Topic: Jump Statements Prepared by Ashwini Y.