Is there a goto statement in Java?
Asked Answered
H

23

294

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?

Hyponitrite answered 30/3, 2010 at 12:30 Comment(12)
just a word of advise: never ever use gotoPageboy
Master Dijkstra says : "Go To Statement Considered Harmful".Check this out : https://mcmap.net/q/24104/-goto-still-considered-harmful-closedLondrina
C mon guys - everyone knows taht GOTO is evil, but that's not answear to the question, is it?Toor
Not just goto, const is also reserved.Ashla
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. ( :-) )Sclar
possible duplicate of alternative to goto statement in JavaFeer
Don't be corrupted. But check out github.com/footloosejava/JavaGotoDonato
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 and just kept the reserved keyword.Bract
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.Histoid
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?Massicot
@Histoid (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...Georgia
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.Atlanta
P
221

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.

Propman answered 30/3, 2010 at 12:33 Comment(3)
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)Imagery
That is good and interesting information, but it doesn't explain why it's still a reserved keyword.Propman
@Propman 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.Soubise
I
254

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

Imagery answered 28/12, 2010 at 17:1 Comment(10)
"...or by extracting a piece of code into a method" - that must be very cool without proper tail call elimination.Tortoiseshell
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.Jaquesdalcroze
@Jaquesdalcroze Usage of goto, judicious as it may be, is always prone to error.Stalky
@Jaquesdalcroze The only use of goto considered good pratice in C++ is backed by the break/continue.Shanteshantee
Goto being a reserved keyword in Java is great because it prevents people from naming labels "goto:".Shanteshantee
grml… I now have to rewrite a small piece of code in larger and less readable because Java™ does not support gotoAstto
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 ...Sclar
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?Endless
@Endless there’s an obvious difference between “most … uses” and a single anecdote about some your coworker. So obvious that it doesn’t even work as a joke.Orms
lol. Exactly what I said, just few developer's anecdote "goto" uses, and they ban "goto", will Java now remove class as well? Just teach the noobs how to use goto and class ;-)Endless
P
221

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.

Propman answered 30/3, 2010 at 12:33 Comment(3)
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)Imagery
That is good and interesting information, but it doesn't explain why it's still a reserved keyword.Propman
@Propman 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.Soubise
C
165

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;
    }
}
Cradlesong answered 30/3, 2010 at 12:36 Comment(10)
Wouldn't this only break the inner loop?Bandsman
@Zoltán No - it redirects the code to the label, right before the first loop.Spears
@Spears 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.Cradlesong
"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.Gentilesse
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!Burgenland
Shouldn't the loops label be after the loops?Illuminative
@Illuminative 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".'Collyer
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.Abash
It's a good idea to indent the stuff that's supposed to be in the label. See here.Rame
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.Grannia
L
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. "

Libertarian answered 30/3, 2010 at 12:32 Comment(5)
"unsigned" is not even there! (sigh)Georgia
Makes sense, since all primitive types in Java are signed.Orbit
@Orbit Not all. "char" is a primitive type and it's unsigned.Uncurl
@SergeyKrivenkov Yes, but char is not designed to store numbers. It's designed so that it can store more types of characters. However, unlike C or C++, Java doesn't support unsigned numbers.Rame
@Orbit I meant that they didn't even "reserve it for future use", meaning unsigned support in Java cannot ever be considered. Which is the saddest thing...Georgia
G
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 :)

Grimes answered 26/8, 2009 at 12:40 Comment(2)
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...Tetrahedron
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.Grimes
Z
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.

Zenas answered 30/3, 2010 at 12:35 Comment(2)
goto is reserved, but not for future use.Bract
and what about the 10% when it would be needed ?Billposter
R
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
Rabaul answered 11/4, 2013 at 10:53 Comment(0)
A
12

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.

Adamsen answered 14/6, 2012 at 13:25 Comment(5)
"program control flow is done completely with goto". Well, not always unconditional goto.Brucine
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.Paraformaldehyde
"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". ;-)Nigro
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.Atlanta
"I have never used one, so I can't verify this." - That's what language specifications are for :-)Sclar
M
11

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");
     }
}
Minny answered 26/8, 2009 at 12:40 Comment(6)
-1 Why should I not be allowed to have a variable or method named goto?Unreadable
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.Minny
What would a variable 'print' be used for? The words that you have mentioned are more like method names than variables or keywords.Minny
-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.Chiaroscuro
"not recommending it" = it's poor style - not that break and continue are badMinny
@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].Randirandie
D
11

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.

Disarticulate answered 30/3, 2010 at 12:39 Comment(0)
H
10

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

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

Homeopathist answered 30/3, 2010 at 12:32 Comment(3)
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?Shaffert
@Sri Kumar : see @applechewer's answer, it exists but it's not implemented.Stellastellar
@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.Aharon
U
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.

Unreadable answered 30/3, 2010 at 12:34 Comment(4)
I really hope goto isn't supported in the near future at least ;)Homeopathist
@Bozho: well, it could be used for some ingenious new feature that has absolutely nothing to do with the bad old "harmful" goto.Unreadable
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.Atlanta
@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.Unreadable
M
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");
 }
Meatiness answered 16/9, 2020 at 17:20 Comment(0)
S
3

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

  • return

  • break

  • break label

  • throw inside try-catch-finally

Sorption answered 26/8, 2009 at 18:14 Comment(10)
Exceptions should NEVER be used for flow controlLicht
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.Sorption
@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.Histoid
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 confusionsSenseless
@Senseless You could try returnNorthrop
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.Sorption
@AndrewLazarus I want to skip half of the method, not the entire method.Senseless
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.Atlanta
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?Atlanta
@Senseless You could put the part of the method you want to skip in a label (see here), 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.Rame
C
3

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?

Christianechristiania answered 20/1, 2017 at 15:4 Comment(0)
R
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.

Rustic answered 30/3, 2010 at 12:36 Comment(0)
M
1

To prohibit declarations of variables with the same name.

e.g. int i = 0, goto;

Marivelmariya answered 26/8, 2009 at 12:40 Comment(2)
But why? Why shouldn't we be allowed to make these declarations?Halfdan
D'Oh. Why can't you call a variable 'for' or 'else'? PL/1 had no reserved words, and you could writeAtlanta
M
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 :)

Madelynmademoiselle answered 26/8, 2009 at 12:48 Comment(1)
The link doesn't specify when goto was banished into the reserved word underworld; it just says "not used".Rame
T
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.

Talos answered 30/3, 2010 at 13:28 Comment(0)
F
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.

Fabulist answered 1/4, 2013 at 20:44 Comment(5)
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.Histoid
@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".Fabulist
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.Histoid
@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: #3150754Fabulist
"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 questionVasilek
P
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

Penitence answered 25/9, 2016 at 14:43 Comment(0)
B
-2

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

Bernadinebernadotte answered 29/1, 2013 at 16:18 Comment(2)
Then why doesn't the language have a load keyword?Halfdan
@gribnit, having a goto in bytecode doesn't by itself mean anything for upper level reserved words.Histoid
F
-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; 
            }   
   }
Friede answered 10/8, 2017 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.