What is an alternative function for the goto keyword in Java?
Since Java does not have a goto.
Alternatives to the “goto” are “break” and “continue”.
Unlike C++, Java does not support the goto statement. Instead, it has label . Labels are used to change the flow of the program and jump to a specific instruction or label based on a condition.
Use of goto can be simply avoided using break and continue statements.
The keywords const and goto are reserved, even though they are not currently used. true , false , and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.
You could use a labeled BREAK statement:
search: for (i = 0; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } } }
However, in properly designed code, you shouldn't need GOTO functionality.
There isn't any direct equivalent to the goto
concept in Java. There are a few constructs that allow you to do some of the things you can do with a classic goto
.
break
and continue
statements allow you to jump out of a block in a loop or switch statement.break <label>
allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).continue <label>
to continue with the next iteration of an outer loop from an inner loop.return
.None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from continue
) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code2.
1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the fillInStackTrace()
method. The downside is that the exception's printStackTrace()
methods won't give you useful information ... should you ever need to call them.
2 - The spaghetti code syndrome spawned the structured programming approach, where you limited in your use of the available language constructs. This could be applied to BASIC, Fortran and COBOL, but it required care and discipline. Getting rid of goto
entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With