The break keyword in Java programming language
In this tutorial, we will discuss The break keyword in Java programming language.
the break is a keyword in Java programming language which causes the loop to terminate or to exit execution of for loop, while loop, do-while loop and switch case statements.
When the break statement is used in a loop, the loop terminates immediately during execution.
Declaration
The syntax of break statements given below
break;
Break in while loop
while(.....){ //loop statements break; }
break statement how to use while loop
public class Break_Key{ public static void main(String args[]){ int count=1; while(count<=10) { System.out.println(count); if(count==5){ break; } count++; } } }
When the above code is executed, it produces the following results
1 2 3 4 5
Break in for loop
for(.....){ //loop statements break; }
break statement how to use for loop
public class Break_Key1{ public static void main(String args[]){ int count; for(count=1; count<=10; count++ ) { System.out.println(count); if(count==4){ break; } } } }
When the above code is executed, it produces the following results
1 2 3 4
Break in switch nstatements
switch(.....){ //case statements 1 break; //case statements 2 break; .......... .......... }
break statement how to use switch statements
public class SwitchKey{ public static void main(String args[]){ int age=18; switch(age){ case 1: System.out.println("Baby"); break; case 5: System.out.println("child"); break; case 10: System.out.println("boy"); break; case 15: System.out.println("student"); break; case 18: System.out.println("teen ager"); break; default:System.out.println("man"); } }
When the above code is executed, it produces the following results
teen ager
There are other Java language keywords that are similar to this keyword
Suggested for you