Is there a goto statement in Java?

前端 未结 23 1948
醉酒成梦
醉酒成梦 2020-11-22 04:50

I\'m confused about this. Most of us have been told that there isn\'t any goto statement in Java.

But I found that it is one of the keywords in Java. Where can it be

相关标签:
23条回答
  • 2020-11-22 05:36

    I'm not a fan of goto either, as it usually makes code less readable. However I do believe that there are exceptions to that rule (especially when it comes to lexers and parsers!)

    Of Course you can always bring your program into Kleene Normalform by translating it to something assembler-like and then write something like

    int line = 1;
    boolean running = true;
    while(running)
    {
        switch(line++)
        {
            case 1: /* line 1 */
                    break;
            case 2: /* line 2 */
                    break;
            ...
            case 42: line = 1337; // goto 1337
                    break;
            ...
            default: running = false;
                    break;
        }
    }
    

    (So you basically write a VM that executes your binary code... where line corresponds to the instruction pointer)

    That is so much more readable than code that uses goto, isn't it?

    0 讨论(0)
  • 2020-11-22 05:37

    goto is not in Java

    you have to use GOTO But it don't work correctly.in key java word it is not used. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

       public static void main(String[] args) {            
                GOTO me;
                //code;
                me:
                //code; 
                }   
       }
    
    0 讨论(0)
  • 2020-11-22 05:38

    So they could be used one day if the language designers felt the need.

    Also, if programmers from languages that do have these keywords (eg. C, C++) use them by mistake, then the Java compiler can give a useful error message.

    Or maybe it was just to stop programmers using goto :)

    0 讨论(0)
  • 2020-11-22 05:39

    James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.

    Source: James Gosling, Q&A session

    0 讨论(0)
  • 2020-11-22 05:39

    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html

    "The keywords const and goto are reserved, even though they are not currently used. "

    0 讨论(0)
  • 2020-11-22 05:39

    Note that you can replace most of the benign uses of goto by

    • return

    • break

    • break label

    • throw inside try-catch-finally

    0 讨论(0)
提交回复
热议问题