Java basics 2: break keywords, java Basics
The break in Java is generally used to jump out of a switch or loop.
Do not go into details when jumping out of the switch.
The break Jump Out Loop usually jumps out of the current loop.
If you need to jump out of a multi-tier loop, you can add a label after the break, and then mark the label before you need to jump out of the layer loop. This usage is similar to a goto statement.
This may not be very clear. You can see the following code at a glance.
public class Lesson03_1 { public static void main(String[] args) { Lesson03_1 l31 = new Lesson03_1(); l31.go(); System.exit(0); } public void go() { String o = ""; z: for (int x = 0; x < 4; x++) { zz: for (int y = 0; y < 2; y++) { for (int k = 0; k < 5; k++) { if (x == 1) break; if (x == 2 && y == 1) break zz; o = o + x + y; } } } System.out.print(o); }}
When it is executed to break;, it is to jump out of the loop at the last layer and execute the zz layer.
When the break zz; is executed, the zz loop exists and the layer z is executed.
※※In fact, tags can be applied to any statement, or even to the if statement or block statement, as shown below:
public static void main(String[] args) { lable: { System.out.println("haha"); if(true) break lable; System.out.println("gaga"); } System.out.println("heihei");}
Print result:
hahaheihei
Visible System. out. println ("gaga"); not executed
※※A break statement is similar to a goto statement and is not recommended as a goto statement.
※※The break statement can only jump out of the statement block.