Java - break Statement-interview
Q1. What is the purpose of the break statement in Java?
The break statement is used to terminate the nearest enclosing loop (for, while, do-while) or a switch statement immediately, transferring control to the next statement after the loop/switch.
Q2. How does break differ from continue in Java?
break terminates the loop/switch completely, while continue skips the current iteration and moves to the next one.
Q3. Can we use break outside of a loop or switch block?
- Using break outside of loops or switch statements results in a compile-time error.
Q4. What is a labeled break in Java? Give an example.
A labeled break allows breaking out of a specific outer loop in nested loops.
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(j==1) break outer;
}
}
Q5. In which scenarios is break commonly used?
- Exiting a loop early when a condition is met (e.g., searching in an array).
- Exiting a switch case after execution.
- Breaking out of nested loops using labeled break.