Header javaperspective.com
JavaPerspective.com  >   Beginner Tutorials  >   3. Java Basics  >   3.16. The break statement

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
         
}
    }

}

Create a class named App and call the method breakTest:

public class App {

   
public static void main(String[] args) {

         
new JavaLoops().breakTest();

   
}

}

The output is:

0
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

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7