Appearance
Break And Continue
Whether it is a while
loop or a for
loop, there are two special statements that can be used, namely the break
statement and the continue
statement.
break
During the loop, you can use the break
statement to jump out of the current loop. Let's look at an example:
java
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i=1; ; i++) {
sum = sum + i;
if (i == 100) {
break;
}
}
System.out.println(sum);
}
}
When using a for
loop to calculate from 1 to 100, we do not set the detection condition for loop exit in for()
. However, inside the loop, we use if
to judge. If i==100
, we exit the loop through break
.
Therefore, the break
statement is usually used in conjunction with the if
statement. Pay special attention to the fact that the break
statement always jumps out of the loop at which it is located. For example:
java
public class Main {
public static void main(String[] args) {
for (int i=1; i<=10; i++) {
System.out.println("i = " + i);
for (int j=1; j<=10; j++) {
System.out.println("j = " + j);
if (j >= i) {
break;
}
}
// jump here
System.out.println("breaked");
}
}
}
The above code is two for
loops nested. Because the break
statement is located in the inner for
loop, it will break out of the inner for
loop, but not the outer for
loop.
continue
break
will jump out of the current loop, that is, the entire loop will not be executed. continue
ends this loop early and continues directly to the next loop. Let's look at an example:
java
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i=1; i<=10; i++) {
System.out.println("begin i = " + i);
if (i % 2 == 0) {
continue; // This cycle will end
}
sum = sum + i;
System.out.println("end i = " + i);
}
System.out.println(sum); // 25
}
}
Pay attention to the effect of the continue
statement. When i
is an odd number, the entire loop is executed completely, so begin i=1
and end i=1
are printed. When i
is an even number, the continue
statement will end this loop early. Therefore, begin i=2
will be printed but end i=2
will not be printed.
In multi-level nested loops, the continue
statement also ends the current loop.
Summary
The break
statement can jump out of the current loop;
The break
statement is usually used with if
to end the entire loop early when the condition is met;
The break
statement always jumps out of the nearest loop;
The continue
statement can end this loop early;
The continue
statement is usually used with if
to end the loop early when the conditions are met.