Break Statement
Lesson 10 of 11 in Coddy's Control Statements in Java course.
The break statement in the programming world is used to terminate or end an ongoing process.
Say we want to fill a bottle with water, so we turn on the tap, and the bottle starts getting filled with water. As soon as the bottle gets completely filled, we turn the tap off. We ended as soon as the bottle was full, indicating that our work was completed.
This is exactly what the break statement does.
When you encounter a break statement inside a loop, the loop is terminated, and the control jumps to the next line of code.
It breaks the current flow of the program at the specified condition. In the case of an inner loop, it breaks only the inner loop.
Syntax:
break;Challenge
EasyWrite a program that loops through a string prints each character and breaks the loop when the letter is 'o' encountered.
Try it yourself
class BreakString {
public static void breakString(String s) {
// Write code here
}
}All lessons in Control Statements in Java
1What are Control Statements?
Introduction2Decision Making Statments
Simple if Statementif-else Statementif-else-if StatementNested if-StatementSwitch Case Statement