Hi, let’s explore the topic of the Java Break Statement. You can learn the material either in video format with a CodeGym mentor or in a more detailed text version with me below.
Java Break
Break statement in Java is majorly used in the following two cases.- Break quits the loop and jumps out of it (both for and while).
- Break statement exits a case in the switch statement.
Syntax
break;
Example
public class Driver1 {
public static void main(String[] args) {
// Testing break statement in while loop
System.out.println("Test Break statement in While loop");
int i = 0;
while (i < 5) {
if (i == 2) {
break;
}
System.out.println(i++);
}
}
}
Output
Test Break statement in While loop
0
1
Differences between continue and break
The considerable difference between break and continue is that the break exits a loop at once. Once a break statement is executed, the loop will not run again. However, after executing the continue statement, the following lines of code will be skipped for the current iteration only. The loop will begin to execute again.Break and Continue in While Loop
Break and Continue can both be used in a while loop. Let’s look at the example below to have a clear understanding.Example
public class Driver {
public static void main(String[] args) {
// Testing both break and continue statements side by side
String [] weekdays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
System.out.println("Test Break statement in While loop");
System.out.println("\nWorking Days:\n");
int i = 0;
while (i < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
i++;
break;
// Not any working day will be printed
// because the loop breaks on Sunday
// once the loop breaks it moves out of the loop
}
System.out.println(weekdays[i++]);
}
System.out.println("\nTest Continue statement in While loop");
System.out.println("\nWorking Days:\n");
int j = 0;
while (j < weekdays.length ) {
if (weekdays[i].equals("Saturday") || weekdays[i].equals("Sunday")) {
j++;
continue;
// All the working/business days will be printed
// when the loop encounters Saturday or Sunday
// it skips that iteration and continues to the next iteration
}
System.out.println(weekdays[i++]);
}
// A test case for continue statement using for loop
System.out.println("\nTest Continue in For loop");
for (int x = 0; x < 5; x++) {
if (x == 2)
continue;
System.out.println(x);
}
}
}
Output
Test Break statement in While loop
Working Days:
Test Continue statement in While loop
Working Days:
Monday
Tuesday
Wednesday
Thursday
Friday
Test Continue in For loop
0
1
3
4
Conclusion
That was a simple implementation of break vs continue in Java. Hope by the help of the above examples you can understand when to use what. You’re encouraged to practise for learning better. Also, keep us posted with any feedback or questions you might have. Until next time, keep learning and keep growing.More reading: |
|---|
GO TO FULL VERSION