JavaRush /Java Blog /Random EN /break statement in java
iloveski
Level 37
Москва

break statement in java

Published in the Random EN group
Hello to all colleagues and those simply interested.
Break statement in Java - 1
Today we will look at such a feature of the Java programming language as the break operator. This is the first article on the topic of transition operators, so if you like it, I will be glad to write more. I would like to note right away that this article is intended primarily for beginner developers, and more advanced students may not find anything new for themselves here. So, let's go. In Java, there are 2 ways to change the order in which program instructions are executed: jump statements and exception handling mechanism. There are three jump operators in java: break, continue and return. Today I invite you to take a closer look at the operator break. Exception handling is such a broad topic that it is beyond the scope of this article. There are three ways to use the break statement in java. The first and most popular way is to use it breakto exit the loop early, for example:
public class SimpleExample {
    public static void main(String[] args) {
        findNumberInLoop(3);
    }
    public static void findNumberInLoop(int number){
        for (int i = 0; i < 10; i++) {
            if (i == number) {
                break;
            }
            System.out.println(i);
        }
        System.out.println("cycle was finished");
    }
}
This example will display:
1
2
cycle was finished
This means that when the loop counter ibecomes equal to the passed parameter number, that is, the number 3, the loop execution is terminated early. If the program has several nested loops, then break outputs only from the innermost loop, for example:
public class SimpleExample {
    public static void main(String[] args) {
        findNumberInLoop(3);
    }
    public static void findNumberInLoop(int number){
        for(int i = 0; i < 5; i++) {
            for (int j =0; j < 10; j++) {
                if(j == number) {
                    break;
                }
                System.out.print(j);
            }
            System.out.println();
        }
        System.out.println("cycles was finished");
    }
}
This example produces the output:
012
012
012
012
012
cycles was finished
As can be seen from the example, the inner loop is interrupted each time at the number 3 (parameter number), and the outer loop is executed 5 times, as intended. In java, you can use more than one break statement within a loop, but this is not recommended, since the readability and structure of the code is greatly degraded. The second use breakis to use it to interrupt the execution of statements in branches switch, for example:
public class SimpleExample {
    public static void main(String[] args) {
        square(2);
    }

    public static void square(int number){
        switch (number){
            case 1:
                System.out.println(number*number);
                break;
            case 2:
                System.out.println(number*number);
                break;
            case 3:
                System.out.println(number*number);
                break;
        }
        System.out.println("after switch");
    }
}
Running this example will produce the output:
4
after switch
The break statement passed control to the code following the entire block switch. If you do not specify breakin switchin this example:
public class SimpleExample {
    public static void main(String[] args) {
        square(2);
    }
    public static void square(int number){
        switch (number){
            case 1:
                System.out.println(number*number);
            case 2:
                System.out.println(number*number);
            case 3:
                System.out.println(number*number);
        }
        System.out.println("after switch");
    }
}
The output will not be as expected:
4
4
after switch
This happened because after the block was executed, case 2the program continued executing all subsequent case blocks , which gave us the corresponding output. Sometimes this feature of the operator switch can be beneficial to us, for example:
public class SimpleExample {
    public static void main(String[] args) {
        compare(2);
        compare(7);
        compare(12);
    }
    public static void compare(int number){
        switch (number){
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("number is less than 5 or equal 5");
                break;
            case 6:
            case 7:
            case 8:
            case 9:
                System.out.println("number is greater than 5");
                break;
            default:
                System.out.println("number is less than 0 or greater than 9");
        }
        System.out.println("after switch");
    }
}
This program compares a given number with the number 5 and gives the following output:
after switch
number is greater than 5
after switch
number is less than 0 or greater than 9
after switch
When a method is called for the first time, the operator switchtransfers control to the operator case 2and then to the operator breakin case 5. The second call is similar to the first, but starts with c case 7. The third call does not find a suitable value among all cases, so the operator is executed default. The third way is to use the operator breakinstead of the gotoC operator. To do this, we will use a special form of the operator breakcalled breakwith a label. This form looks like break метка;a Label - this is usually any suitable name from the java namespace, preceding a block of code. Moreover, after applying this block of code breakwith a label, the code will continue to be executed from the place after the block with the corresponding label, for example:
public class SimpleExample {
    public static void main(String[] args) {
        howWeUseLabels(true);
        System.out.println();
        howWeUseLabels(false);
    }
    public static void howWeUseLabels(boolean bool) {
        firstBlock:{
            secondBlock:{
                thirdBlock:{
                    System.out.println("We will see it always");
                    if(bool) {
                        break secondBlock;
                    }
                    System.out.println("We won't see it if bool == true");
                }
                System.out.println("We won't see it if bool == true");
            }
            System.out.println("We will see it always");
        }
    }
}
This example will produce the following output:
We will see it always
We will see it always

We will see it always
We won't see it if bool == true
We won't see it if bool == true
We will see it always
After the first method call, the operator breaktransfers control to the end of the block secondBlock, exiting secondBlockand thirdBlock, while executing another operator println()at the end firstBlock. After the second call, all lines are displayed on the screen. Labels can also be used to indicate cycles. It should be remembered that you can only go to a label from inside the block of code indicated by the label; for example, such code will not compile:
public class SimpleExample {
    public static void main(String[] args) {
        label:{
            System.out.println("inside label");
        }
        if(true) {
            break label;
        }
        System.out.println("This is error");
    }
}
Notes on code and statement cleanliness break: There is generally accepted advice to use the statement breakvery carefully, as the use breakmakes the loop more difficult to understand and forces the programmer to look inside the loop to understand the nuances of its operation. There is a heuristic rule that break you can use more confidently in shorter loops and with more caution in long and deeply nested loops, since this increases the likelihood of errors and complicates the reading and understanding of your code by other programmers. As I wrote above, the use of a large number of break. scattered throughout the code indicates that the programmer does not fully understand why he wrote his code the way he did. It might be worth considering refactoring such a loop by breaking it up into several smaller loops. Try to be careful when using break a label as a replacement for goto, as this complicates the code structure. That's all I wanted to tell you today about the operator breakin java. I will be glad to constructive criticism, and I am also ready to write a continuation about operators continueand return, if you are interested.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION