The break keyword is used inside loops (for, while or do-while) or switch-case block.
When used in loops: It ends the loop as soon as it is encountered, thus it is always accompanied by a condition.
When used in switch block: It prevents execution of the next case statement after the execution of previous case statement.
break in for loop
class JavaExample { public static void main(String args[]) { for (int i = 1; i <= 20; i++) { if (i == 3) break; //if i==3 then end the loop System.out.println(i); } } }
Output:
1 2
break in while loop
class JavaExample { public static void main(String args[]) { int i = 1; while(i<=20){ if(i == 3) break; System.out.println(i); i++; } } }
Output:
1 2
break in do-while
class JavaExample { public static void main(String args[]) { int i = 1; //do-while loop do{ if(i == 3) break; System.out.println(i); i++; }while(i<=20); } }
Output:
1 2
break in switch-case block
class JavaExample { public static void main(String args[]) { int i = 1; //switch-case switch(i){ case 1: System.out.println("i value is 1"); break; //end the switch after case 1 is executed case 2: System.out.println("i value is 2"); break; //end the switch after case 2 is executed default: System.out.println("i value is not 1 or 2"); } } }
Output:
i value is 1