Is there a goto statement in Java?
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?
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
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.
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;
}
}