Search code examples
javakeywordgoto

Alternative to a goto statement in Java


What is an alternative function for the goto keyword in Java?

Since Java does not have a goto.


Solution

  • 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.