Alternative to a goto statement in Java

2019-01-02 23:43发布

What is an alternative function for the goto keyword in Java?

Since Java does not have a goto.

11条回答
欢心
2楼-- · 2019-01-02 23:45

While some commenters and downvoters argue that this isn't goto, the generated bytecode from the below Java statements really suggests that these statements really do express goto semantics.

Specifically, the do {...} while(true); loop in the second example is optimised by Java compilers in order not to evaluate the loop condition.

Jumping forward

label: {
  // do stuff
  if (check) break label;
  // do more stuff
}

In bytecode:

2  iload_1 [check]
3  ifeq 6          // Jumping forward
6  ..

Jumping backward

label: do {
  // do stuff
  if (check) continue label;
  // do more stuff
  break label;
} while(true);

In bytecode:

 2  iload_1 [check]
 3  ifeq 9
 6  goto 2          // Jumping backward
 9  ..
查看更多
The star\"
3楼-- · 2019-01-02 23:46

StephenC writes:

There are two constructs that allow you to do some of the things you can do with a classic goto.

One more...

Matt Wolfe writes:

People always talk about never using a goto, but I think there is a really good real world use case which is pretty well known and used.. That is, making sure to execute some code before a return from a function.. Usually its releasing locks or what not, but in my case I'd love to be able to jump to a break right before the return so I can do required mandatory cleanup.

try {
    // do stuff
    return result;  // or break, etc.
}
finally {
    // clean up before actually returning, even though the order looks wrong.
}

http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

The silly interview question associated with finally is: If you return from a try{} block, but have a return in your finally{} too, which value is returned?

查看更多
爷的心禁止访问
4楼-- · 2019-01-02 23:47

If you really want something like goto statements, you could always try breaking to named blocks.

You have to be within the scope of the block to break to the label:

namedBlock: {
  if (j==2) {
    // this will take you to the label above
    break namedBlock;
  }
}

I won't lecture you on why you should avoid goto's - I'm assuming you already know the answer to that.

查看更多
何必那么认真
5楼-- · 2019-01-02 23:47

Java doesn't have goto, because it makes the code unstructured and unclear to read. However, you can use break and continue as civilized form of goto without its problems.


Jumping forward using break -

ahead: {
    System.out.println("Before break");
    break ahead;
    System.out.println("After Break"); // This won't execute
}
// After a line break ahead, the code flow starts from here, after the ahead block
System.out.println("After ahead");

Output:

Before Break
After ahead

Jumping backward using continue

before: {
    System.out.println("Continue");
    continue before;
}

This will result in an infinite loop as every time the line continue before is executed, the code flow will start again from before.

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-02 23:49
public class TestLabel {

    enum Label{LABEL1, LABEL2, LABEL3, LABEL4}

    /**
     * @param args
     */
    public static void main(String[] args) {

        Label label = Label.LABEL1;

        while(true) {
            switch(label){
                case LABEL1:
                    print(label);

                case LABEL2:
                    print(label);
                    label = Label.LABEL4;
                    continue;

                case LABEL3:
                    print(label);
                    label = Label.LABEL1;
                    break;

                case LABEL4:
                    print(label);
                    label = Label.LABEL3;
                    continue;
            }
            break;
        }
    }

    public final static void print(Label label){
        System.out.println(label);
    }
查看更多
Deceive 欺骗
7楼-- · 2019-01-02 23:50

Use a labeled break as an alternative to goto.

查看更多
登录 后发表回答