Java From Beginner To Advanced

0% completed

Previous
Next
Java break Statement

The break statement in Java is used to immediately terminate the current loop or switch statement. It helps in controlling the flow of the program by exiting from a loop or switch when a specific condition is met. The break statement can be very useful in preventing unnecessary iterations or in exiting nested loops.

How It Works

  • Loop Termination: In loops (for, while, do...while), when the break statement is executed, the loop stops and control moves to the statement immediately after the loop.
  • Switch Termination: In switch statements, break prevents the execution from falling through to subsequent cases.
  • Use Case: It is generally used when a condition is met that makes further iteration pointless or potentially harmful.

Syntax

break;
  • The break statement is written inside loops or switch cases.
  • No value is associated with it; simply using break; terminates the loop or switch.

Example 1: Exiting a Loop

Below is an example that uses a for loop to iterate through numbers and breaks out of the loop when the number 3 is reached.

Java
Java

. . . .

Explanation:

  • The loop iterates from 1 to 5.
  • When i equals 3, the break statement is executed, terminating the loop immediately.
  • As a result, only numbers 1 and 2 are printed, and the message after the loop is displayed.

Example 2: Using break in a switch Statement

Below is an example that uses the break statement in a switch case to prevent fall-through.

Java
Java

. . . .

Explanation:

  • The switch statement evaluates the variable day.
  • When day equals 4, the corresponding case prints "Thursday".
  • The break statement prevents the code from executing any subsequent cases, ensuring that only "Thursday" is printed.

By using the break statement, you can control the flow of your loops and switch statements more effectively. It ensures that once a desired condition is met, no unnecessary processing takes place. Experiment with these examples and try modifying the conditions to see how break affects program execution.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next