Java supports three jump operators - Using the operator
The operator Use
In addition to being used in switch statements and loops, Using the operator
Sometimes it is useful to start the next iteration of a loop early. That is, you need to continue executing the loop, but stop processing the rest of the code in its body for this particular iteration. In fact, this is a Operator
The last control statement is
break
, continue
and return
. They transfer control to another part of your program. Let's consider each of the operators in detail.
Using the operatorbreak
The operator break
in Java is used in three cases. First, as you've already seen, it ends the sequence of statements at statement branches switch
. Secondly, it can be used to break out of a loop. Thirdly, it can be used as a "civilized" form of the unconditional jump operator goto
. This section explains the last two cases. Use break
to exit a loop By using break
, you can force the loop to terminate immediately, bypassing the conditional expression and any remaining code in the loop body. When a statement break
is encountered within a loop, the second one ends and program control is transferred to the statement that follows it. Simple example:
// Использование break для выхода из цикла.
public class BreakLoop {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
if (i == 4) {
break; // завершить цикл, если i = 4
}
System.out.println("i: " + i);
}
System.out.println("Цикл завершен.");
}
}
This program generates the following output:
i: 0
i: 1
i: 2
i: 3
Цикл завершен.
Although the loop for
is designed here to execute its statements from 0 to 99 times, the operator break
causes it to terminate early when i is 4. The operator break
can be used with any of Java's loops, including intentionally infinite loops. For example, below is the previous program coded using a loop while
. The output of this program is the same as its predecessor.
// Использование break для выхода из while-цикла.
public class BreakLoop2 {
public static void main(String[] args) {
int i = 0;
while (i < 100) {
if (i == 4) {
break; // закончить цикл, если i = 4
}
System.out.println("i: " + i);
i++;
}
System.out.println("Цикл завершен.");
}
}
When used within a set of nested loops, the statement break
will only exit the innermost loop. For example:
// Использование break во вложенных циклах.
public class BreakLoop3 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.print("Итерация " + i + ": ");
for (int j = 0; j < 10; j++) {
if (j == 4) {
break; // закончить цикл, если j = 4
}
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Цикл завершен.");
}
}
This program generates the following output:
Итерация 0: 0 1 2 3
Итерация 1: 0 1 2 3
Итерация 2: 0 1 2 3
Цикл завершен.
As you can see, the statement break
in the inner loop causes only that loop to terminate. The outer loop is not affected. Let us make two more comments regarding break
. First, multiple statements may appear in a loop break
. However, be careful. Too many of them tend to destructure your code. Second, the break
, which terminates the - operator switch
, affects only the given switch
- operator (and not the loops that include it). Comment: Break
was not designed as a normal means of loop termination. This purpose is served by the loop header conditional expression. The operator break
should only be used to break the loop when certain special situations arise.
Use break
as a formgoto
In addition to being used in switch statements and loops, break
it can also be used alone as a "civilized" form of the goto
. Java does not contain the operator goto
because it performs the branch in an arbitrary and unstructured way. Code that uses . intensively goto
is typically difficult to understand and maintain. It also overrides some compiler optimizations. There are, however, several places in a program where goto
control flow is a valuable and legitimate construct. For example, goto
it can be useful when you are breaking out of a deeply nested set of loops. To handle such situations, Java defines an extended form of the operator break
. Using it, you can exit one or more blocks of code. These blocks do not need to be part of a loop or statement switch
. This can be any block. Next, you can determine exactly where execution will continue because this form break
works with the mark and provides the benefits of goto
, bypassing its problems. A break
labeled statement has the following general form: break label;
Here label
is the name of a label that identifies some block of code. When this form break
is executed, control is transferred from the named block of code (whose label is specified in the statement break
) to the statement following that block. A marked block of code must include this statement break
, but it is not required that this inclusion be direct (that is, break
it can be included not directly in a block with its own label, but in a block nested within it, possibly also marked). This means that you can use a marked operator break
to escape from a set of nested blocks. But you can't use break
a block of code that doesn't include a break
. To name a block, place a label at the beginning of the block (before the opening curly brace). A label is any valid Java identifier followed by a colon. After labeling a block, its label can be used as an argument to the operator break
. This will cause execution to continue from the end of the marked block. For example, the following program contains three nested blocks, each with its own label. The operator break
moves forward, beyond the end of the block marked with the label second
, skipping two operators println()
.
// Использование break How цивorзованной формы goto.
public class Break {
public static void main(String[] args) {
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Перед оператором break.");
if (t) {
break second; // выход из блока second
}
System.out.println("Данный оператор никогда не выполнится");
}
System.out.println("Данный оператор никогда не выполнится ");
}
System.out.println("Данный оператор размещен после блока second.");
}
}
}
Running this program generates the following output:
Перед оператором break.
Данный оператор размещен после блока second.
One of the most common uses of the labeled operator break
is to escape nested loops. For example, in the following program the outer loop is executed only once:
// Использование break для выхода из вложенных циклов.
public class BreakLoop4 {
public static void main(String[] args) {
outer:
for (int i = 0; i < 3; i++) {
System.out.print("Итерация " + i + ": ");
for (int j = 0; j < 100; j++) {
if (j == 10) {
break outer; // выйти из обоих циклов
}
System.out.print(j + " ");
}
System.out.println("Эта строка никогда не будет выведена");
}
System.out.println("Цикл завершен.");
}
}
The program generates the following output:
Итерация 0: 0 1 2 3 4 5 6 7 8 9 Цикл завершен.
It is easy to see that when the inner loop is interrupted before the end of the outer one, both loops end. Keep in mind that you cannot do break
a -jump to any label that is not defined for the enclosing block. For example, the following program is invalid and will not compile:
// Эта программа содержит ошибку.
public class BreakErr {
public static void main(String[] args) {
one:
for (int i = 0; i < 3; i++) {
System.out.print("Итерация " + i + ": ");
}
for (int j = 0; j < 100; j++) {
if (j == 10) {
break one; //He верно!
}
System.out.print(j + " ");
}
}
}
Because a loop marked one does not include a statement break
, it is not possible to transfer control to this block.
Using the operatorcontinue
Sometimes it is useful to start the next iteration of a loop early. That is, you need to continue executing the loop, but stop processing the rest of the code in its body for this particular iteration. In fact, this is a goto
transition past the next body operations to the end of the loop block. This action is performed by the operator continue
. In loops, the while
and do while
operator continue
causes control to be transferred directly to the conditional expression that controls the loop. In a loop, for
control passes first to the iterative part of the statement for
and then to the conditional expression. For all three loops, any intermediate code is bypassed. An example program that uses continue
to print two numbers on each line is given below:
// Демонстрирует continue.
public class Continue {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
if (i % 2 == 0) {
continue;
}
System.out.println("");
}
}
}
This code uses the operation %
(modulo) to check if something is i
even. If so, the loop continues without printing a newline character. Program output:
0 1
2 3
4 5
6 7
8 9
As with the , operator break
, continue
you can define a label indicating which enclosing loop to continue. An example program that uses continue
to print a triangular multiplication table from 0 to 9.
// Использование continue с меткой.
public class ContinueLabel {
public static void main(String[] args) {
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
The statement continue
in this example ends the loop evaluating j
, and continues with the next iteration of the loop driven by i
. Output from this program:
0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
It is extremely rarely useful continue
. One reason for this is that Java provides a rich set of looping statements that suit most applications. However, for those special situations in which it is necessary to terminate the iteration early, the statement continue
provides a structured way to accomplish this task.
Operatorreturn
The last control statement is return
. It is used to explicitly return from a method, that is, it transfers program control back to the calling program. The operator return
is classified as a transition operator. Although its full discussion must wait until the methods are discussed, a brief overview is provided here return
. The operator return
can be used anywhere in a method to jump back to the program calling the method. The statement return
immediately ends execution of the method it is in. The following example illustrates this:
// Демонстрирует return.
public class Return {
public static void main(String[] args) {
boolean t = true;
System.out.println("Перед оператором return.");
if (t) {
return; // возврат в вызывающую программу
}
System.out.println("Этот оператор никогда не выполнится.");
}
}
This return
returns to the Java system at runtime, since it is the system that calls the main()
. Output from this program:
Перед оператором return.
You may notice that the final statement println()
is not executed. At execution time, return
control is transferred back to the calling program. One final note. In the previous program, the if
(t) operator is necessary. Without it, the Java compiler would throw an "unreachable code" error because it would know that the last statement println()
would never be executed. To prevent this error, the (t) operator is used if
; it tricks the compiler for the sake of this demonstration. Link to original source: Transition operators
GO TO FULL VERSION