What is an alternative function for goto keyword in java? Since Java does not have goto.
You could use 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 a properly designed code, you shouldn't need GOTO functionality.
If you really want something like goto statements, you could always try breaking to named blocks.
You have to be within the scope of the block to break to the label:
namedBlock: {
if (j==2) {
// this will take you to the label above
break namedBlock;
}
}
I won't lecture you on why you should avoid goto's - I'm assuming you already know the answer to that.
There is no direct equivalent to the goto
concept in Java. There are two constructs that allow you to do some of the things you can do with a classic goto
.
- The
break
andcontinue
statements allow you to jump out of a block in a loop or switch statement. - A labeled statement and
break <label>
allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block). - Throwing and catching exceptions allows you to (effectively) jump out of many levels of method call. (However, exceptions is relatively expensive, and are considered to be a bad way to do "ordinary" control flow.)
- And of course, there is
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 and FORTRAN codes.
Just for fun, here is a GOTO implementation in Java.
Example:
1 public class GotoDemo { 2 public static void main(String[] args) { 3 int i = 3; 4 System.out.println(i); 5 i = i - 1; 6 if (i >= 0) { 7 GotoFactory.getSharedInstance().getGoto().go(4); 8 } 9 10 try { 11 System.out.print("Hell"); 12 if (Math.random() > 0) throw new Exception(); 13 System.out.println("World!"); 14 } catch (Exception e) { 15 System.out.print("o "); 16 GotoFactory.getSharedInstance().getGoto().go(13); 17 } 18 } 19 }
Running it:
$ java -cp bin:asm-3.1.jar GotoClassLoader GotoDemo 3 2 1 0 Hello World!
Do I need to add "don't use it!"?