Java Break Statement

In Java, the break statement is a control flow statement that is used to terminate the execution of a loop or switch statement. When a break statement is encountered inside a loop or switch statement, the program immediately exits the loop or switch and continues executing the code that follows.

Here's an example of how a break statement can be used in Java to exit a for loop when a condition is met:

                
    for (int i = 1; i <= 10; i++) {
      if (i == 5) {
        break;
      }
      System.out.println(i);
    }
                
            

In this example, the for loop executes 10 times, with the value of i incrementing from 1 to 10. Inside the loop, the program checks whether i is equal to 5 using an if statement. If i is equal to 5, the program executes a break statement, which immediately exits the for loop. If i is not equal to 5, the program prints the value of i to the console using the System.out.println() method.

The output of this program is:

                
    1
    2
    3
    4
                
            

Because the break statement is encountered when i is equal to 5, the program exits the loop before the value of i reaches 6.

The break statement can also be used in a switch statement to exit the switch early. For example:

                
    int dayOfWeek = 3;
    String dayName;

    switch (dayOfWeek) {
      case 1:
        dayName = "Monday";
        break;
      case 2:
        dayName = "Tuesday";
        break;
      case 3:
        dayName = "Wednesday";
        break;
      case 4:
        dayName = "Thursday";
        break;
      case 5:
        dayName = "Friday";
        break;
      default:
        dayName = "Unknown";
        break;
    }

    System.out.println(dayName);
                
            

In this example, the program uses a switch statement to assign a string value to the dayName variable based on the value of dayOfWeek. When dayOfWeek is equal to 3, the program executes the code inside the case 3: block and assigns the value "Wednesday" to dayName. The program then executes a break statement, which immediately exits the switch statement. The program then prints the value of dayName to the console using the System.out.println() method, which outputs "Wednesday".

Overall, the break statement is a powerful tool for controlling the flow of execution in Java programs. It allows programs to exit loops or switch statements early when certain conditions are met, which can be useful in a wide variety of programming tasks.