Over a million developers have joined DZone.

Goto In Java

·
After my C finite state machine, I figured I'd sink to new levels of depravity by figuring out how to write GOTO in Java. Here's the result.

Usual disclaimer about "if you use this code then the baby Jesus will cut kittens".

Update: Thanks to roots_ on freenode ##java for the suggestion of using a do { } while(false) instead, and cybereal for pointing out that I didn't need the label.


public class Goto
{
    public static int END = Integer.MAX_VALUE;

    public static void main(String[] args)
    {
        int _goto = 0;

        do
        {
            switch(_goto)
            {
                case 0:
                case 1:
                    System.out.println("Foo");
                    _goto = 3;
                    continue;
                
                case 2:
                     System.out.println("Baz");
                    _goto = END;
                    continue;
                case 3:
                     System.out.println("Bar");
                    _goto = 2;
                    continue;
             }
        } while(false)
    }
}

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}