Pages

Tuesday, September 5, 2017

Java Break Statement With Examples


Java break statement is used in a loop or switch case. If it encounters inside a loop then it terminates the loop and continues execution after the loop.

While loops in Java

It can be used to terminate a case in the switch statement.

Switch statement in java

Syntax:

break;

Flow Chart:

Java Break statement


Break Statement Example:

package com.adeepdrive.switchdemo;
public class BreakExample {
    public static void main(String[] args) {
        int number = 1;
        while (number <= 10) {
            System.out.println("number : " + number);
            if (number == 5) {
                System.out.println("break statement");
                break;
            }
            number++;
        }
        System.out.println("After while loop.");
    }
}

Output:

number : 1
number : 2
number : 3
number : 4
number : 5
break statement
After while loop.

In the above program if we comment the break line then we will get the number from 1 to 10. But, we have added the condition if number is 5 then used break statement. That means indicated to stop the loop and come out to execute after the loop.

Break in two while loops:

Break statement behavior is different if we use it in nested loops. See the below example and output.

package com.adeepdrive.switchdemo;
public class BreakExample {
    public static void main(String[] args) {
        int oddNumber = 1;
        int evenNumber = 0;
        while (evenNumber <= 10) {
            oddNumber = 1;
            System.out.println("Even : " + evenNumber);
            while (oddNumber <= 10) {
                System.out.print(oddNumber + " ");
                if (oddNumber == 5) {
                    break;
                }
                oddNumber = oddNumber + 2;
            }
            System.out.println();
            evenNumber = evenNumber + 2;
        }
        System.out.println("After while loop.");
    }
}

Output:

Even : 0
1 3 5
Even : 2
1 3 5
Even : 4
1 3 5
Even : 6
1 3 5
Even : 8
1 3 5
Even : 10
1 3 5
After while loop.

Even though the break statement is present, it coming out only from the current while loop but not from outer while loop.

Note: Always break is to the specific to the current loop but not for its outer loops.

Java Break statement

No comments:

Post a Comment

Please do not add any spam links in the comments section.