Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using The break Statement in Java http://www.chankok.com/java-use-the-break-statement/
public class BreakStatementExample {
public static void main(String[] args) {
// Using break statement in for loop
System.out.println("Using break statement in for loop");
for (int count = 1; count <= 10; count++) {
if (count == 6) {
break;
}
System.out.println(count);
}
// Using break statement in enhanced for loop
System.out.println("Using break statement in enhanced for loop");
int[] counts = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int count: counts) {
if (count == 6) {
break;
}
System.out.println(count);
}
// Using break statement in while loop
System.out.println("Using break statement in while loop");
int count1 = 1;
while (count1 <= 10) {
if (count1 == 6) {
break;
}
System.out.println(count1);
count1++;
}
// Using break statement in do-while loop
System.out.println("Using break statement in do-while loop");
int count2 = 1;
do {
if (count2 == 6) {
break;
}
System.out.println(count2);
count2++;
} while (count2 <= 10);
// Using break statement in switch statement
System.out.println("Using break statement in switch statement");
String day = "Thursday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.printf("%s is weekday%n", day);
break;
case "Saturday":
case "Sunday":
System.out.printf("%s is weekend%n", day);
break;
default:
System.out.printf("%s is an invalid day%n", day);
}
}
}
public class LabeledBreakStatementExample {
public static void main(String[] args) {
// Labeled break statement to terminate and exit the outer for loop
outerLoop:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
if (i == 3 && j == 3) {
break outerLoop;
}
System.out.printf("i = %d, j = %d%n", i, j);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment