JavaRush /Java Blog /Random EN /Jump statements
articles
Level 15

Jump statements

Published in the Random EN group
Java supports three jump operators - break, continueand return. They transfer control to another part of your program. Let's consider each of the operators in detail. Jump statements - 1

Operator usagebreak

An operator breakin Java is used in three ways. First, as you have already seen, it ends the sequence of statements in statement branches switch. Second, it can be used to break out of a loop. Third, it can be used as a "civilized" form of the unconditional branch operator goto. This section explains the last two cases. Using breakto Break Out of a Loop By using break, you can force immediate termination of the loop, bypassing the conditional expression and any remaining code in the loop body. When a statement breakis encountered within a loop, the second one ends and program control is transferred to the statement following 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 foris designed here to run its statements from 0 to 99 times, the statement breakcauses it to terminate early when i is equal to 4. The statement breakcan be used with any of Java's loops, including intentionally infinite loops. For example, the previous program is shown below, encoded with a loop while. The output of this program is the same as that of 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 inside a set of nested loops, the statement breakwill only exit from 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 breakin the inner loop causes only that loop to terminate. The outer loop is not affected. Let's make two more remarks about break. First, multiple statements may appear in the loop break. However, be careful. Too many of them tend to destructure your code. Second, the break, which terminates the statement switch, affects only the given switch-statement (and not the loops that include it). Comment: Breaknot designed as a normal means of terminating a cycle. The loop header conditional expression serves this purpose. The statement breakshould only be used to break the loop when some special situation occurs.

Use breakas a formgoto

In addition to being used in switch statements and loops, breakit can also be used alone, as a "civilized" form of the goto. Java does not contain the operator gotobecause it performs the jump in an arbitrary and unstructured way. Code that uses heavily gotois usually difficult to understand and maintain. It also undoes some compiler optimizations. There are, however, several places in a program where gotois a valuable and legitimate flow control construct. For example, gotoit can be useful when you exit a deeply nested set of loops. To handle such situations, Java defines an extended form of the operatorbreak. 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. It can be any block. Further, you can specify exactly where the execution will continue, because the given form breakworks with the label and provides the benefits gotoof bypassing its problems. A breaklabeled statement has the following general form: break label; Here labelis the name of a label that identifies some block of code. When this form breakis executed, control is transferred from the named block of code (whose label is specified in the statement break) to the statement following that block. The marked block of code must include the given statement break, but this inclusion is not required to be direct (i.e.,breakmay not be included directly in a block with its own label, but in a block nested in it, possibly also labeled). This means that you can use the labeled statement breakto exit a set of nested blocks. But you can't use it breakto transfer control to 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 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. Operatorbreakjumps forward past the end of the block labeled with second, skipping two statements 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 a labeled statement breakis to exit 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 loop, both loops end. Note that you cannot breakjump 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 + " ");
    }
  }
}
Since the loop marked as one does not include a statement break, it is not possible to transfer control to this block.

Operator usagecontinue

Sometimes it is useful to start the next iteration of the loop early. That is, you need to continue the execution of the loop, but stop processing the rest of the code in its body for this particular iteration. In fact, this is a gototransition past the next operations of the body to the end of the loop block. This action is performed by the operator continue. In loops, the whileand do whilestatement continuecauses control to be transferred directly to the conditional expression that controls the loop. In the loop, forcontrol passes first to the iterative part of the operator forand then to the conditional expression. For all three loops, any intermediate code is bypassed. An example program that uses continueto 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 remainder) to check if is ieven. If so, the loop continues without printing the newline character. Program output:
0 1
2 3
4 5
6 7
8 9
As with the statement break, you can define a label in continue, indicating which enclosing loop to continue. An example program that uses continueto 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 continuein this example ends the loop that evaluates jand continues with the next iteration of the loop driven by i. The output of 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
continueVery rarely useful . One reason for this is that Java provides a rich set of loop statements that will suit most applications. However, for those special situations in which early termination of the iteration is necessary, the operator continueprovides 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 programmatic control back to the calling program. The operator returnbelongs to the category of transition operators. Although a full discussion of it must wait until a discussion of methods, a brief overview is provided here return. The operator returncan be used anywhere in a method to jump back to the program that called the method. The operator returnimmediately ends the execution of the method in which it resides. This is illustrated by the following example:
// Демонстрирует return.
public class Return {

  public static void main(String[] args) {
    boolean t = true;
    System.out.println("Перед оператором return.");
    if (t) {
      return; // возврат в вызывающую программу
    }
    System.out.println("Этот оператор никогда не выполнится.");
  }
}
Here, returnreturns to the Java system at runtime, since that system is the one that calls the main(). The output of this program:
Перед оператором return.
You may notice that the final statement println()is not executed. At execution time, returncontrol is transferred back to the calling program. And the last remark. In the previous program, the operator if(t) is needed. 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, ifit cheats the compiler for the sake of this demonstration. Link to the original source: Jump operators
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION