Developer Insights

20 GOTO 10

Where Java still surprised me after all these years

Sander Verhagen | May 25, 2016

20 GOTO 10, infinite loop (can’t argue with Urban Dictionary). It is the higher language equivalent of the “jump” instruction (JMP) used to change the instruction pointer register, in assembly language. GOTO is a keyword that I first encountered in the BASIC computer language, and there we used it all over the place. You created flow through your program by “going to” some line number. In Visual Basic you don’t use line numbers, but you jump to a label, like so:

Then we grew up and were taught that it was bad! Bad programmer you — for using GOTO. The well-respected, influential and also Dutch computer scientist Edsger Dijkstra famously declared the GOTO statement “harmful”. GOTO‘s Wikipedia page has a big paragraph about that and other criticisms. There is a lot said and written about if and that and why GOTO is bad. (Even Reddit chimed in. I’ve heard you, young kids, hang out on that site a lot.)

Then fast-forward to present day. I’ve been writing Java for a decade now (haven’t touched much BASIC for much longer than that). And I had never expected to find jumps and labels in Java. I found some inside Hibernate source code. And out of sheer amazement I decided to share this with my fellow Java programmers. It’s not quite a GOTO statement, so my introduction may be a little misleading. Instead it lets you put a label to indicate where to jump to, when breaking out of a nested loop. Something like this:

Note how a plain break would have only exited the inner for-loop. By the way, it works for the continue keyword too.

It seems like a useful application of labels, and it is nice that it is restricted to only the case of controlling particular nested constructs, without the risk infesting code bases in the same way GOTO did. Again, I was just amazed to learn this “hidden” (to me) keyword after all this time. If you had known of this Java language feature all along… then… please just keep walking.

One more link: Branching Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)