Introduction
The execution of a Java program is done in sequential order. Looping statements like for, while, and do-while are used to execute a set of statements repeatedly. If such an execution were to continue, it would go on forever. This can be prevented by adding appropriate terminating conditions to the loop or by implementing jump statements.
A jump statement in Java helps transfer the control of a program from one line of the code to another and skip the ones in between.
Jumping statements are control statements that move program execution from one location to another. Jump statements are used to shift program control unconditionally from one location to another within the program. Jump statements are typically used to abruptly end a loop or switch-case.
Types of Jump Statements in Java
- Break Statement
- Continue Statement
- Return Statement
1. Break Statement
Break statements in Java is used in three ways:
Using Break Statement to exit a loop
In Java, the break statement is used to exit loops prematurely, similar to how it's used in other programming languages. You can use it within for, while, and do-while loops to stop the loop's execution when a specific condition is met. The syntax for using the break statement in Java is as follows:
while loop:
for loop:
Use Break as a form of goto
In Java, the break statement is not directly used as a form of goto. The break statement is specifically designed to exit from loops prematurely, and it cannot be used to jump to arbitrary locations in the code like a traditional goto statement.
The goto statement is unavailable in Java because it can lead to confusing and hard-to-maintain code. Instead, Java encourages using structured programming constructs like loops, conditional statements, and methods to control the flow of the program.
Use Break In a Switch case
In Java, we can use the break statement within a switch case to exit the switch block and prevent fall-through to subsequent cases. Here's an example:
Output:
Wednesday
Explanation:
In this example, the break statement is used after each case to exit the switch block. This prevents the flow from falling through to subsequent cases. If day is, for example, 3, only "Wednesday" will be printed, and the switch statement will terminate after that case.