Java break keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 18 August 2019   |   Print Email
In Java, the break keyword stops execution of for loop, while loop and switch-case construct. The execution goes to next statement after the construct is broken.
The following example shows a break statement inside a for loop:
for (int count = 0; count < 100; count++) { System.out.println("count = " + count); if (count > 70) { break; } }
The above for loop prints values of count from 0 to 70.
The following example shows break statement is used in a while loop:
int number = 0; while (true) { number++; System.out.println("number = " + number); if (number > 1000) { break; } }
The above while loop will stop when the value of number is greater than 1000.
The following example shows break statements are used in every case of the switch statement:
int monthNumber = 2; String monthName = ""; switch(monthNumber) { case 1: monthName = "January"; break; case 2: monthName = "February"; break; case 3: monthName = "March"; break; case 4: monthName = "April"; break; } System.out.println("The month is " + monthName);
The above code will produce the output: The month is February. The break statements prevent the execution from falling through from one case to another.
See all keywords in Java.
Related Topics:
- Java for loop examples
- Java while loop examples
- Java swith-case examples
- Some notes about execution control statements in Java
Other Recommended Tutorials:
- Primitive data types in Java
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
Comments