Site icon TestingDocs.com

Java break Statement

Overview

In this post, we will discuss the Java break statement. Sometimes we may come across situations where we want to terminate the loop.

When a break statement is executed, the loop is terminated and the control is transferred to the next statement outside the loop. We can use the break statement in all the loops in Java.

break statement

We can use the break statement to terminate the loop immediately. The control of the program reaches the next statement after the loop. The break statement is mostly used to force an early termination of a loop.

Example

We will illustrate the use of the break statement through the following code listing:

/*
 * break statement demo
 * Java Tutorials - www.TestingDocs.com
 * 
 */
public class BreakDemo {

	public static void main(String[] args) {
		int i = 0;
		while (i < 10) {
			i++;
			if (i == 5) {  // terminate the loop when i is 5
				break;
			}
			System.out.println("i= "+ i);
		} 
	}
}


Program Output

i= 1
i= 2
i= 3
i= 4

Another Example

Let’s see the usage in a for loop.

public class BreakDemo {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    for (int i = 1; i < 100; i++) {
        if (i == 7) {
          break; // The loop will terminate when i reaches 7
        }
        System.out.println("i=" +i);
      } 
  }
}

 

 

 

In the case of nested loops, the break statement terminates the innermost loop, and the control jumps to the next outer loop that surrounds the loop.

The main difference between a break and a continue statement is that the break terminates the entire loop, whereas the continue statement skips the current iteration of the loop.

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version