Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Break
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
In Java, there are branching statements, for example the break statement, which breaks the loop in the program and continues running the statements after the loop. If you have a for or while loop and you want it to stop after a certain condition is true, you can have a break statement inside the if statement. How is it implemented in code? Take a look below.
BreakStatementExample.java
package exlcode;
public class BreakStatementExample {
public static int exampleVariableOne = 10;
public static void main(String[] args) {
System.out.println("Counting forward from 0-10:");
for (int count = 0; count <= exampleVariableOne; count++) {
System.out.print(count + " ");
// once count is equal to 5, the break statement will
// terminate the for loop
if (count == 5) {
break;
}
}
}
}
The if statement has the expression "count == 5", so when count has a value of 5 the statements inside the if statement will be executed, including the break; statement, which will terminate the for loop so any number after 5 will not be printed. break; does not affect the if statement, it terminates the whole loop. When the break; statement is used appropriately, it saves time when running the program because you wouldn't have to loop through the same statements over and over again.