Thursday, June 20, 2019

break Statement in Java

In this tutorial you’ll learn about break statement in Java. When you are working with loops where loop body is repeatedly executed, you may have a scenario where you want to skip the execution of statements inside the loop or you may want to terminate the loop altogether. To handle these two scenarios there are two control statements in Java- continue and break. In this tutorial you’ll learn about Java break statement along with usage examples.

Where do you use break statement in Java

break statement in Java can be used in following scenarios-

  1. For terminating a loop– If there is a break statement with in a for loop, while loop or do-while loop the loop is terminated and the control moves to the statement immediately following the loop.
  2. For terminating switch statement– In Java switch statement if a case is followed by a break statement then the switch statement is terminated. For usage of break statement with switch statement in Java refer this post- Switch-Case Statement in Java
  3. Using labeled break statement– You can use labeled break statement to exit out of a labelled block.

break statement Java examples

1- Using break statement to break out of a for loop. In the example a list of cities is iterated and searched for a specific city. If the city is found loop is terminated using a break statement.

public class BreakJava {

    public static void main(String[] args) {
        List<String> cities = Arrays.asList("Beijing", "London", "Santiago", "St. Petersburg", "Helsinki");
        for(String city : cities) {
            if(city.equals("Santiago")) {
                System.out.println("Found city - " + city);
                // terminate loop
                break;
            }                
        }
        System.out.println("Out of for loop");
    }
}

Output

Found city - Santiago
Out of for loop

2- Using break statement to terminate an infinite while loop.

public class BreakJava {

    public static void main(String[] args) {
        int i = 1;
        while(true){
            // terminate loop when i is greater than 5
            //display i's value otherwise
            if(i > 5)
                break;
            System.out.println("i- " + i);
            i++;
        }
    }
}

Output

i- 1
i- 2
i- 3
i- 4
i- 5

3- When break statement is used with nested loops, break statement terminates the innermost loop in whose scope break is used.

public class BreakJava {

    public static void main(String[] args) {
        for(int i = 1; i <= 3; i++){
            System.out.print(i + "- ");
            for(int j = 0; j < 10; j++){
                System.out.print("*");
                // terminate inner loop
                if(j == 6)
                    break;
            }
            System.out.println();                   
        }        
        System.out.println("Out of loop");
    }
}

Output

1- *******
2- *******
3- *******
Out of loop

Here break statement is used in the scope of outer loop so outer for loop is terminated.

public class BreakJava {

    public static void main(String[] args) {
        for(int i = 1; i <= 6; i++){
            if(i == 4)
                break;
            System.out.print(i + "- ");
            for(int j = 0; j < 10; j++){
                System.out.print("*");
            }
            System.out.println();                   
        }        
        System.out.println("Out of loop");
    }
}

Output

1- **********
2- **********
3- **********
Out of loop

4- With unlabeled break statement you can come out of the innermost loop. If you want to come out of a deeply nested loop you can use labeled break statement which helps in coming out of more than one blocks of statements.

For example in the following code two for loops are there and labeled break statement helps in coming out of both the loops.

public class BreakJava {

    public static void main(String[] args) {
        int[][] array = { 
            {1, 2, 3 },
            {4, 5, 6 },
            {7, 8, 9 }
        };
        int searchedNum = 5;
        boolean flag = false;
        int i = 0, j = 0;
        // label
        outer:
        for (i = 0; i < array.length; i++) {
            for (j = 0; j < array[i].length; j++) {
                if (array[i][j] == searchedNum) {
                    flag = true;
                    // lebeled break
                    break outer;
                }
            }
        }
        if(flag) {
            System.out.println("Found element " + searchedNum + " at index " + i + " and " + j );
        }else {
            System.out.println("Element " + searchedNum + " not found in the array" );
        }
    }
}

Output

Found element 5 at index 1 and 1

That's all for this topic break Statement in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. if else Statement in Java With Examples
  2. Arithmetic And Unary Operators in Java
  3. this Keyword in Java With Examples
  4. Constructor in Java
  5. Abstract Class in Java

You may also like-

  1. BigInteger in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. Map.Entry Interface in Java
  4. Deadlock in Java Multi-Threading
  5. Selection Sort Program in Java
  6. How to Display Pyramid Patterns in Java - Part1
  7. Python First Program - Hello World
  8. How MapReduce Works in Hadoop

No comments:

Post a Comment