Home » Java Basics » break/continue statement » Break Statement

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Break Statement

This is an example of how to use the break statement. The break statement can be used to terminate a for, while, or do-while loop. In the example the break statement is used when checking an array’s elements, as described:

  • Create a for statement with an int index from 0 up to an int array length, that checks the elements of the array.
  • When an element divided to 2 returns 0, then the break statement is used that terminates the for loop.

Let’s take a look at the code snippet that follows:  
 

package com.javacodegeeks.snippets.basics;

public class BreakStatement {
	
	public static void main(String[] args) {

		int array[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

		System.out.println("Printing first even number");
		
		for (int i = 0; i < array.length; i++) {
			if (array[i] % 2 ==0)
				break;
			else
				System.out.print(array[i] + " ");
		}

	}

}

Output:

Printing first even number
1 

  
This was an example of how to use the break statement in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of