In Java, the break keyword stops execution of for loop, while loop and switch-case construct. The execution goes to next statement after the construct is broken.

The following example shows a break statement inside a for loop:

for (int count = 0; count < 100; count++) {
    System.out.println("count = " + count);
    if (count > 70) {
        break;
    }
}

The above for loop prints values of count from 0 to 70.

The following example shows break statement is used in a while loop:

int number = 0;
while (true) {
    number++;
    System.out.println("number = " + number);
    if (number > 1000) {
        break;
    }
}

The above while loop will stop when the value of number is greater than 1000.

The following example shows break statements are used in every case of the switch statement:

int monthNumber = 2;
String monthName = "";
switch(monthNumber) {
    case 1:
        monthName = "January";
        break;
    case 2:
        monthName = "February";
        break;
    case 3:
        monthName = "March";
        break;
    case 4:
        monthName = "April";
        break;
}
System.out.println("The month is " + monthName);

The above code will produce the output: The month is February. The break statements prevent the execution from falling through from one case to another.

See all keywords in Java.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment