Goto Statement In Java

Goto Statement

In this article we will be discussing about Goto Statement in Java.

A goto statement in any  programming language provides an unconditional jump from the goto to a labeled statement in the same function.

Goto function

Goto Statement 

Goto Statement in Java isn’t supported by Java. It is reserved as a keyword in the Java Virtual Machine,In case if they want to add it in a later version.
Instead of Goto function, Java uses Label. Labels are used to change the flow of the program and jump to a specific instruction or label based on a condition.

Use of Break And Continue in Label :

Break and continue are used to break or to continue the program when the label function is called. These are the two reserved keywords in Java Virtual Machine.

Use case of break statement with label:

 

Goto Statement in java

Run

public class label {
    public static void main(String[] args){
        Lakshit:
            for (int i = 1; i <= 5; i++) {
                for (int j = 1; j <= 5; j++) {
                    if (j == 2)
                        break Lakshit;
                    System.out.println("PrepInsta " + j);
                }
            }   
    }
}

 

Output:

PrepInsta 1

 

Use case of Continue statement with label:
Run
public class label {
    public static void main(String[] args){
        Lakshit:
            for (int i = 1; i <= 5; i++) {
                for (int j = 1; j <= 5; j++) {
                    if (j == 2)
                        continue Lakshit;
                    System.out.println("PrepInsta " + j);
                }
            }   
    }
}
Output:

PrepInsta 1
PrepInsta 1
PrepInsta 1
PrepInsta 1
PrepInsta 1
PrepInsta 1