Java

Goto in Java

Java supports structured programming constructs like loops, methods, etc. to organize and understand code better. It doesn’t support the Goto statement. Although it was present in some earlier programming languages, Java has eliminated it to enhance code readability and maintainability. In Java, “label” can be utilized instead of the Goto statement.

This post will provide the Java equivalent of the Goto statement along with suitable examples.

Goto in Java

Like other programming languages, including C or C++, Java doesn’t support the Goto statement. However, it supports “labels” that can be used in place of the Goto statement. In Java, labels can be used before nested loops, and the “break” keyword can be used with the label to break/jump out of a specific outer loop. Ultimately, it allows better control over the loop execution. Furthermore, the labels can also be used with the continue keyword.

For practical demonstration, check out the below-stated examples.

Example 1: Label With “break” Keyword

To set the label with the “break” keyword, first of all, specify a label named “outer” inside the Java “main()” method:

outer:

 

In this stated code snippet, we will iterate the elements through the “for” loop. Then, inside the loop invoke the “print()” method to show/print the resultant output. Furthermore, add another “for” iterator and test the condition using the “if” statement. When the condition is evaluated according to the specified value, the “break” keyword will terminate the loop:

for (int i = 0; i < 3; i++){
 System.out.print("Pass " + i + ": ");
 for (int j = 1; j < 50; j++) {
  if (j == 20) {
   break outer;
  }
   System.out.print(j + " ");
 }
 System.out.println("Not printed");
}

 

Then, invoke the “println()” for printing the “Complete Loop” message on the screen:

System.out.println("Complete Loop");

 

Output

It can be observed that the loop is terminated when the condition is evaluated as true:

Example 2: Label With “continue” Keyword

You can also utilize the label along with the continue keyword to iterate the outer loop according to the given condition. To do so, first, specify the “outer” label:

outer:

 

Now, iterate the elements with the help of the “for” loop. Within the “for” iterator, set the condition and use the “continue” keyword along with an “outer” label:

for (int i = 0; i < 10; i++) {
 for (int j = 0; j < 10; j++) {
  if (j == 2)
 continue outer;
  System.out.println("j value = " + j);
 }
}

 

Output

That’s all about the Goto or alternative of Goto in Java.

Conclusion

Like many other programming languages, Java does not support the Goto Statement. However, Java programming support labels that can be used as an equivalent of the Goto statement. You can determine the label name along with the “break” keyword to break out the particular outer loop. This post has explained how to achieve the functionality of the Goto statement in Java.

About the author

Hafsa Javed