3.16. The break statement
Last updated: 27 January 2013.
You may have already seen a break statement example in the tutorial The switch statement. In fact, the break statement can also be used with the for, for-each, while and do-while statements. The break statement exits the most closely enclosing for, for-each, while, do-while or switch statement. In the example shown below, the method breakTest prints the positive integers under 10 to the standard output using an infinite loop:
public class JavaLoops {
public void breakTest(){
final int MAX_VALUE = 10;
int i = 0;
while(true){ // infinite loop
System.out.println(i);
++i;
if(i >= 10)
break; // exit the loop if i >= 10
}
}
}
public void breakTest(){
final int MAX_VALUE = 10;
int i = 0;
while(true){ // infinite loop
System.out.println(i);
++i;
if(i >= 10)
break; // exit the loop if i >= 10
}
}
}
Create a class named App and call the method breakTest:
public class App {
public static void main(String[] args) {
new JavaLoops().breakTest();
}
}
public static void main(String[] args) {
new JavaLoops().breakTest();
}
}
The output is:
0
1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9
You are here :
JavaPerspective.com >
Beginner Tutorials >
3. Java Basics >
3.16. The break statement
Next tutorial : JavaPerspective.com > Beginner Tutorials > 3. Java Basics > 3.17. The return statement
Next tutorial : JavaPerspective.com > Beginner Tutorials > 3. Java Basics > 3.17. The return statement