DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Goto In Java

04.13.2007
| 48010 views |
  • submit to reddit
        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)
    }
}