Slide 1
Slide 2
Slide 3

Label break in java programming (V40)

No Comments

Labeled break and continue

Break Label

A break label in Java is an extended form of the regular break statement, which allows you to terminate an outer loop from inside a nested loop. Unlike the normal break, which only exits the nearest loop, a labeled break can be used to exit multiple loops at once.

Syntax:

Source Code:

Copied!
public class breakLabel {
    public static void main(String[] args) {
        outerLoop: // Label
        for (int i = 0; i < 3; i++) { //outer loop
            for (int j = 0; j < 3; j++) { //inner loop
                System.out.println("i: " + i + ", j: " + j);
                if (i == 1 && j == 1) {
                    break outerLoop; // Exits both loops
                }
            }
        }
        System.out.println("Exited from loops.");
    }
}

Result:

Source Code:

Copied!
import java.util.Scanner;

public class labelGuessing {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int secretNumber = 7; // Hidden number

        guessLoop:
        while (true) {
            System.out.print("Guess the number (1-10): ");
            int guess = scanner.nextInt();

            if (guess == secretNumber) {
                System.out.println("Congratulations! You guessed it.");
                break guessLoop; // Exit the loop
            } else {
                System.out.println("Wrong guess. Try again.");
            }
        }
        scanner.close();
    }
}

Result:

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top