Goto in Java

Unlike C++, Java does not support the goto statement. Instead, it has label. Labels are used to change the flow of the program and jump to a specific instruction or label based on a condition. The following illustration may help you to better understand what a label is.

svg viewer

Break and continue

break and continue are the two reserved key-words that instruct a program to change its workflow. As the name suggests, the continue statement instructs the program counter to stay in the flow of the program and causes the control flow to go to the next iteration of the loop; thus, skipping over the remainder of the loop body. The continue statement does not come out of the scope of the label.

The break statement instructs the program counter to jump out of the innermost enclosing loop of a statement. The remaining iterations of the loop are not executed. This is used to come out of the scope of the label immediately.

continue code

The following code skips when printing number 33.

class myClass {
public static void main( String args[] ) {
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
continue label; //skips 3
}
System.out.println(i);
}
}
}

break code

The following code does not print any number that comes after 22.

class myClass {
public static void main( String args[] ) {
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
break label; // exits the loop when it reaches 3
}
System.out.println(i);
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved