288

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 used? If it can not be used, then why was it included in Java as a keyword?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Venkat
  • 20,802
  • 26
  • 75
  • 84
  • 18
    just a word of advise: never ever use goto – lostiniceland Aug 26 '09 at 12:39
  • 7
    Master Dijkstra says : "Go To Statement Considered Harmful".Check this out : http://stackoverflow.com/questions/46586/goto-still-considered-harmful – n00ki3 Aug 26 '09 at 12:43
  • 9
    C mon guys - everyone knows taht GOTO is evil, but that's not answear to the question, is it? – Martin Lazar Aug 26 '09 at 14:31
  • 2
    Not just goto, const is also reserved. – Dan Dyer Aug 26 '09 at 23:58
  • 25
    The real reason is that the "g**o" word is consider obscene in most programming languages. The Java designers are just protecting innocent young programmers from corrupting influences. ( :-) ) – Stephen C Mar 30 '10 at 12:50
  • 2
    possible duplicate of [alternative to goto statement in Java](http://stackoverflow.com/questions/2430782/alternative-to-goto-statement-in-java) – H H Aug 19 '12 at 20:41
  • Don't be corrupted. But check out https://github.com/footloosejava/JavaGoto – The Coordinator May 16 '14 at 21:36
  • 2
    Several answers here state that it is reserved for future use, which isn't correct. The truth is that Gosling [got rid of it from a very early version](http://www.artima.com/intv/gosling3P.html) and just kept the reserved keyword. – user207421 Dec 01 '14 at 03:24
  • 41
    The witch-hunt against goto has spawned some of the most aggravating moments in my life. I've seen people contort C code by hiding functionality in functions, put absurd exit logic in multi-nested loops, and otherwise do every form of over-engineering imaginable JUST to avoid someone criticizing their code in a code-review. This rule, along with the "thou must avoid multiple returns" canard, is steeped in nonsense. There are times when goto makes things less maintainable. There are times when goto makes things more maintainable. I was so hoping this witch-hunt would have died in the 80's. –  Feb 04 '15 at 17:35
  • 2 years since I learned programming, this is the first time I see a good use of `goto`, I mean, it could be useful. Or to say: Why remove a feature in the first place? – OverCoder Apr 27 '16 at 22:14
  • 2
    @user4229245 (you don't exist anymore, this is for posterity) funny enough: `goto` is the *only* branching instruction known by the processor executing our code, and the *only* one we, programmers, are forbidden to use... – Matthieu Mar 18 '17 at 16:58
  • Key here is whether you want to write algorithms, or write machine code using syntactic saccharine (which is basically fake syntactic sugar). If you have to use gotos, you are writing assembly code with grotesque syntax. The job of writing assembly code belongs to compilers. Get over it, dude. – flounder Oct 30 '20 at 11:33

23 Answers23

247

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

Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
  • 26
    "...or by extracting a piece of code into a method" - that must be very cool without proper tail call elimination. – Display Name Mar 21 '13 at 10:08
  • 61
    Sometimes, a judicious use of `goto` **is** the most readyble and clear way to express something, so forcing it into anything else is perforce **less readable**. – Deduplicator Oct 28 '14 at 18:32
  • 2
    @Deduplicator Usage of goto, judicious as it may be, is always prone to error. – Çelebi Murat Jan 25 '17 at 14:02
  • @Deduplicator The only use of goto considered good pratice in C++ is backed by the break/continue. – Winter Jun 23 '17 at 16:59
  • 3
    Goto being a reserved keyword in Java is great because it prevents people from naming labels "goto:". – Winter Jun 23 '17 at 17:01
  • 2
    grml… I now have to rewrite a small piece of code in larger *and* __less__ readable because Java™ does not support `goto`… – mirabilos Jun 22 '20 at 14:30
  • Readability is always a matter of opinion. For a start, it depends on the reader. But the opinion(s) of a language designer trump the opinions of someone who merely uses the language ... – Stephen C Jan 25 '21 at 00:04
  • **Most "`goto`" uses are not confusing and/or evil, few developer's use may be;** I remember a co-worker who created a `class` named `UserLogin` and another named `UserLogout` (his wrong loose-coupling), joke: Will Java now remove `class` as well? – Top-Master Nov 24 '22 at 19:17
217

The Java keyword list specifies the goto keyword, but it is marked as "not used".

It was in the original JVM (see answer by @VitaliiFedorenko), but then removed. It was probably kept as a reserved keyword in case it were to be added to a later version of Java.

If goto was not on the list, and it gets added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etc...) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 29
    `This was probably done in case it were to be added to a later version of Java.` Actually, the main reason is a little bit different (see my answer below) – Vitalii Fedorenko Dec 28 '10 at 17:03
  • 2
    That is good and interesting information, but it doesn't explain why it's still a reserved keyword. – Thomas Dec 04 '14 at 07:47
  • @Thomas Didn't you describe why it's reserved? It's a keyword, so it can't be used now; later goto could spring to life without causing problems. If it wasn't a reserved word, it could be used now to produce code (int goto = 2;) which would break if goto was introduced. –  Mar 20 '15 at 15:09
163

The keyword exists, but it is not implemented.

The only good reason to use goto that I can think of is this:

for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        goto outsideloops; // to break out of both loops
    }
}
outsideloops:

In Java you can do this like this:

loops:
for (int i = 0; i < MAX_I; i++) {
    for (int j = 0; j < MAX_J; j++) {
        // do stuff
        break loops;
    }
}
jonnystoten
  • 7,055
  • 2
  • 28
  • 36
  • Wouldn't this only break the inner loop? – Zoltán Oct 25 '11 at 13:05
  • 1
    @Zoltán No - it redirects the code to the label, right before the first loop. – assylias May 16 '12 at 12:07
  • 24
    @assylias Well, not quite. The label labels the outer loop. Then `break loops` means "break out of the loop called `loops`". Maybe in retrospect a better name for the label might have been `outer`. – jonnystoten May 16 '12 at 12:34
  • 12
    "The only good reason to use goto" Quick and dirty little programs that need an unconditional infinite loop make great use of goto. Using `while (true) {` ... `}` is overkill. GOTO is frequently stigmatized for its improper uses, but I argue that unnecessary comparisons to boolean literals is worse than GOTO. – Alexander Jan 22 '14 at 17:39
  • I agree. I needed countless times `goto` for breaking nested loops. I believe, it is useful only for this. Thanks for `break LABEL;` syntax. I am not familiar with it! – Chameleon Jan 17 '16 at 13:13
  • 1
    Shouldn't the loops label be after the loops? – GC_ Aug 17 '16 at 16:14
  • @GC_ Reading the comment further above yours, by 'jonnystoten', should explain why it's written that way: 'The label labels the outer loop. Then break loops means "break out of the loop called loops".' – naki Jan 01 '18 at 06:50
  • 3
    I recently discovered, that this labeling technique is also very usefull in combination with a `continue LABEL;` statement. Thus you can continue an outer lying loop. – infotoni91 Mar 21 '18 at 11:29
  • It's a good idea to indent the stuff that's supposed to be in the label. See [here](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html). – Tech Expert Wizard Nov 28 '20 at 13:00
  • 1
    In my opinion Java's use of labels is more confusing and error-prone than the regular labels used with goto in C. They tried to kill goto, but couldn't, and ended up with something even worse. – Georgie Jun 23 '21 at 05:43
43

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. "

Isaac E
  • 1,019
  • 2
  • 8
  • 14
30

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 :)

dave
  • 11,641
  • 5
  • 47
  • 65
  • 1
    The missing goto functionality in Java should be reason enough not to use goto - there is no need to reserve it as a keyword. Following you logic, everything would be a keyword, since it's either used by other languages and/or the Java designers COULD use it in future... – stuXnet Aug 19 '14 at 14:32
  • 1
    I do not think that my logic implies everything would be a keyword. There's a small set of keywords in use across many programming languages that can usefully be detected and handled in Java. Java reserved `goto` and `const` reflecting its C/C++ heritage but they remain unimplemented (although there have been debates about implementing the latter). A couple more like `assert` and `enum` were not initially reserved, but perhaps should have been, given they have been implemented. But hindsight's a wonderful thing. – dave Aug 24 '14 at 01:35
24

They are reserved for future use (see: Java Language Keywords)

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

The reason why there is no goto statement in Java can be found in "The Java Language Environment":

Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.

Pang
  • 9,564
  • 146
  • 81
  • 122
Heinzi
  • 167,459
  • 57
  • 363
  • 519
18

An example of how to use "continue" labels in Java is:

public class Label {
    public static void main(String[] args) {
        int temp = 0;
        out: // label
        for (int i = 0; i < 3; ++i) {
            System.out.println("I am here");
            for (int j = 0; j < 20; ++j) {
                if(temp==0) {
                    System.out.println("j: " + j);
                    if (j == 1) {
                        temp = j;
                        continue out; // goto label "out"
                    }
                }
            }
        }
        System.out.println("temp = " + temp);
    }
}

Results:

I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
andrew
  • 3,083
  • 4
  • 24
  • 29
11

It is important to understand that the goto construct is remnant from the days that programmers programmed in machine code and assembly language. Because those languages are so basic (as in, each instruction does only one thing), program control flow is done completely with goto statements (but in assembly language, these are referred to as jump or branch instructions).

Now, although the C language is fairly low-level, it can be thought of as very high-level assembly language - each statement and function in C can easily be broken down into assembly language instructions. Although C is not the prime language to program computers with nowadays, it is still heavily used in low level applications, such as embedded systems. Because C's function so closely mirrors assembly language's function, it only makes sense that goto is included in C.

It is clear that Java is an evolution of C/C++. Java shares a lot of features from C, but abstracts a lot more of the details, and therefore is simply written differently. Java is a very high-level language, so it simply is not necessary to have low-level features like goto when more high-level constructs like functions, for, for each, and while loops do the program control flow. Imagine if you were in one function and did a goto to a label into another function. What would happen when the other function returned? This idea is absurd.

This does not necessarily answer why Java includes the goto statement yet won't let it compile, but it is important to know why goto was ever used in the first place, in lower-level applications, and why it just doesn't make sense to be used in Java.

  • "program control flow is done completely with goto". Well, not always unconditional goto. – Peter Mortensen Feb 29 '16 at 22:51
  • 1
    Jumping with "goto" from one function into a label in another function is also not possible in C/C++. Goto in C/C++ is restricted to a single function block. – user2328447 Mar 12 '17 at 23:44
  • "it simply is not necessary to have low-level features like goto when more high-level constructs" - remember "Necessity and sufficiency". It's just "not necessary". And thus no reason. What IS a reason: "Goto" as an "high level" substitute for Assembler's JMPs, BNEs and more is reasonable if you want to jump to "executable code" but Java is bytecode and thus not "executable". ;-) – reichhart Dec 12 '18 at 14:21
  • I have heard that C and C++ have goto statements. I have never used one, so I can't verify this. And I've been using C since 1975. It is said that C is a language that gives you all the power of assembly code with all the expressive elegance of assembly code. As such, goto exists only as syntactic saccharine on machine code. It's like syntactic sugar, only fakier. – flounder Oct 30 '20 at 11:37
  • *"I have never used one, so I can't verify this."* - That's what language specifications are for :-) – Stephen C Jan 25 '21 at 00:09
10

Because it's not supported and why would you want a goto keyword that did nothing or a variable named goto?

Although you can use break label; and continue label; statements to effectively do what goto does. But I wouldn't recommend it.

public static void main(String [] args) {

     boolean t = true;

     first: {
        second: {
           third: {
               System.out.println("Before the break");

               if (t) {
                  break second;
               }

               System.out.println("Not executed");
           }

           System.out.println("Not executed - end of second block");
        }

        System.out.println("End of third block");
     }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pjp
  • 17,039
  • 6
  • 33
  • 58
  • 10
    -1 Why should I not be allowed to have a variable or method named goto? – Michael Borgwardt Aug 26 '09 at 12:49
  • 4
    Because it has a meaning in the land of programming which is not applicable to Java. It's also a poor choice of variable name. – pjp Aug 26 '09 at 12:52
  • What would a variable 'print' be used for? The words that you have mentioned are more like method names than variables or keywords. – pjp Aug 26 '09 at 14:45
  • 4
    -1: First of all, just because Java doesn't support "goto" flow control statement, doesn't mean that's the reason it has the "goto" keyword that doesn't do anything. Second, "goto" might be a poor variable name, but it can be an excellent method name, which we can't use because "goto" is a keyword. Third, "break label" and "continue label" exist for a very good reason, so "not recommending it" is not very useful. And fourth, since Sun says it's "not currently used", it most likely means that they once planned to implement , but didn't want to get rid of the keyword when they decided otherwise. – Vojislav Stojkovic May 26 '10 at 02:47
  • "not recommending it" = it's poor *style* - not that `break` and `continue` are bad – pjp Jun 11 '10 at 12:12
  • 2
    @VojislavStojkovic That's just crazy talk. 1) That *is* why it does nothing is because it doesn't support it. According to the JLS `The keywords const and goto are reserved, even though they are not currently used. This may allow a Java compiler to produce better error messages if these C++ keywords incorrectly appear in programs.` This means "We don't use it, so if you're coming from a C++ background we're not going to let you use it at all.". 2) `goto` is a terrible method name. Sorry. 3) break and continue are recommended, but *not in the way used here*. 4) "most likely" [citation needed]. – corsiKa Mar 04 '14 at 23:32
10

No, goto is not used, but you can define labels and leave a loop up to the label. You can use break or continue followed by the label. So you can jump out more than one loop level. Have a look at the tutorial.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94
9

No, thankfully, there isn't goto in Java.

The goto keyword is only reserved, but not used (the same goes for const).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • May i know What the reserved meant here? If using goto and const in code isn't a good practice, Why do they reserve it? Can you please explain? – Gopi Mar 30 '10 at 12:52
  • @Sri Kumar : see @applechewer's answer, it exists but it's not implemented. – Valentin Rocher Mar 30 '10 at 13:35
  • 1
    @Sri Kumar: Reserved keywords prevent them from being used as variable names or similar. This way, these keywords can be implemented in future versions of Java without breaking old source code that could have otherwise used them. – Peter Di Cecco Mar 30 '10 at 13:50
7

No, goto is not used in Java, despite being a reserved word. The same is true for const. Both of these are used in C++, which is probably the reason why they're reserved; the intention was probably to avoid confusing C++ programmers migrating to Java, and perhaps also to keep the option of using them in later revisions of Java.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • 1
    I really hope `goto` isn't supported in the near future at least ;) – Bozho Mar 30 '10 at 12:35
  • 6
    @Bozho: well, it *could* be used for some ingenious new feature that has absolutely nothing to do with the bad old "harmful" goto. – Michael Borgwardt Mar 30 '10 at 12:43
  • Supporting goto would be a giant step backward in program methodology. It is banned for good and sufficient reasons, and does not need to exist. Really, it does not need to exist. For any reason imaginable. – flounder Oct 30 '20 at 11:40
  • @flounder: I fully agree about the *functionaliy* of a direct jump to an arbitrary point in the code being something that should be gone for good except in machine language/assembler. But the *keyword* `goto` may be resurrected for some other, better purpose. – Michael Borgwardt Oct 30 '20 at 12:54
5

Yes is it possible, but not as nice as in c# (in my opinion c# is BETTER!). Opinions that goto always obscures software are dull and silly! It's sad java don't have at least goto case xxx.

Jump to forward:

 public static void main(String [] args) {
   myblock: {
     System.out.println("Hello");
     if (some_condition)
       break myblock; 
     System.out.println("Nice day");
   }
   // here code continue after performing break myblock
   System.out.println("And work");
 }

Jump to backward:

 public static void main(String [] args) {
   mystart: //here code continue after performing continue mystart
   do {
     System.out.println("Hello");
     if (some_condition)         
       continue mystart; 
     System.out.println("Nice day");
   } while (false);
   System.out.println("And work");
 }
mirij
  • 89
  • 1
  • 7
3

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

  • return

  • break

  • break label

  • throw inside try-catch-finally

starblue
  • 55,348
  • 14
  • 97
  • 151
  • 5
    Exceptions should NEVER be used for flow control – ChssPly76 Aug 26 '09 at 23:39
  • 16
    Exceptions _are_ used for flow control, but should be used only for exceptional cases. For example, one of the uses of goto in C is error-handling, especially if it involves cleaning up. – starblue Aug 27 '09 at 05:09
  • 2
    @starblue, you took the words out of my mouth. Throwing an exception *is* control flow. In C, in fact, you can somewhat cleanly implement exception handling via setjmp/longjmp by making sure you first setjmp to the handling code and executing longjmp()ing to it on exception. –  Feb 04 '15 at 18:24
  • I want to do an if check and skip the half of the method if true. Without go to I must use a giant else . IMO it is pretty ugly as too many paranthesis creates confusions – WVrock Dec 20 '15 at 19:33
  • 1
    @WVrock You could try `return` – Andrew Lazarus Feb 01 '16 at 04:13
  • Note that I wouldn't consider a `goto` benign if it could be replaced by `continue`, so `continue` is intentionally left out from the list. – starblue Feb 05 '16 at 07:49
  • @AndrewLazarus I want to skip half of the method, not the entire method. – WVrock Mar 08 '16 at 16:29
  • setjmp/longjmp are among the worst ideas ever implemented. They are seriously a very bad idea. To throw a longjmp, you have to have access to the setjmp block, which is not possible to do in a modular fashion. I came to C from a language that supported exceptions, and was appalled when I discovered setjmp/longjmp. If there is a worse way to implement exceptions, I haven't seen it in nearly six decades as a professional programmer. – flounder Oct 30 '20 at 11:42
  • Also, the statement that exceptions should never be used for control flow is nonsense. An exception is *exactly* a means of achieving control flow. In fact, if it wasn't, then why is it that it changes control flow? – flounder Oct 31 '20 at 22:10
  • 1
    @WVrock You could put the part of the method you want to skip in a label (see [here](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html)), and then break the label if you find that you don't need that part. However, you'll have to put your conditional logic inside the label or it won't work. – Tech Expert Wizard Nov 28 '20 at 13:14
2

As was pointed out, there is no goto in Java, but the keyword was reserved in case Sun felt like adding goto to Java one day. They wanted to be able to add it without breaking too much code, so they reserved the keyword. Note that with Java 5 they added the enum keyword and it did not break that much code either.

Although Java has no goto, it has some constructs which correspond to some usages of goto, namely being able to break and continue with named loops. Also, finally can be thought of as a kind of twisted goto.

Thomas Pornin
  • 72,986
  • 14
  • 147
  • 189
1

To prohibit declarations of variables with the same name.

e.g. int i = 0, goto;

Karl
  • 3,170
  • 1
  • 21
  • 28
1

See the following link is shows all java reserved words and tells you what versions they where added.

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

goto is reserved, even though it is not currently used, never say never however :)

Paul Whelan
  • 16,574
  • 12
  • 50
  • 83
1

http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto

If you have been told that there is no goto statement in Java you have been fooled. Indeed, Java consists two layers of 'source' code.

Lindlof
  • 2,152
  • 2
  • 17
  • 26
  • 6
    that's like saying that any language has a goto because there exists an unconditional branch in the assembly code underneath it all. Having the goto in the byte code doesn't mean that there is a goto in java because "in java" means "In the java language", and byte code is not a layer of source. –  Feb 04 '15 at 18:19
  • @tgm1024, "in Java" can also be interpreted as "in Java platform". Java compiler needs to produce Java bytecode or output won't work in Java platform JVM. C++, for example, doesn't specify compilation output and compiler is free to produce any form of machine code (or any other code). Java bytecode programmed application can be called "Java application" but machine code programmed application can't be called "C++ application". – Lindlof Feb 07 '15 at 11:29
  • 2
    I know full well what java bytecode is. I was first coding in java in 1996. And you can have other languages generate java bytecode for the JVM. Where I'm correcting you is this idea that there are two layers of source. There are not. You have java source and this is compiled to java byte code (executed by the JVM) and this is not an additional layer of source. Just because there is a "goto" in the byte code does not mean that there is a "goto" in java. Java has named breaks and named continues, but no goto. –  Feb 08 '15 at 16:45
  • @tgm1024 I was woken up by a downvote :) It can easily seem that I lost the argument since you made the last comment and your credentials are impressive. My point, which I was building up to, was that it's very possible to program with Java bytecode. To assure you, here's even a question about that: http://stackoverflow.com/questions/3150254/programming-in-java-bytecode – Lindlof Feb 05 '16 at 07:11
  • "it's very possible to program with Java bytecode", and even if that were possible (we know it is possible but anyway), the answer is not pertinent to the precise question –  Aug 18 '21 at 10:53
1

It's very much considered one of those things you Do Not Do, but was probably listed as a reserved word to avoid confusion for developers.

Dean J
  • 39,360
  • 16
  • 67
  • 93
1

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

Of course it is keyword, but it is not used on level of source code.

But if you use jasmin or other lower level language, which is transformed to bytecode, then "goto" is there

user1722245
  • 2,065
  • 1
  • 18
  • 31
-2

Because although the Java language doesn't use it, JVM bytecode does.

gribnit
  • 21
  • 1
-6

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; 
            }   
   }
m-tech
  • 338
  • 2
  • 14