Java - goto keyword
Java does not support goto statement. It is kept as a reserved keyword for future. As an alternative, Java supports labels with break and continue statement.
We can use label within loops as well as in block statements.
Syntax
// break using label in loop
outer: {
for (...){
for (...){
break outer;
}
}
}
// continue using label in loop
outer: {
for (...){
for (...){
continue outer;
}
}
}
// break using label in statement
outer: {
inner: {
break outer;
}
}
// continue using label in statement
outer: {
inner: {
continue outer;
}
}
Following example shows the use of break statement in block statements. We've defined a label outer over a block and in that block we're having another inner block. In inner block, we're breaking to outer block based on a condition. As outer block is not executed completedly, only statement of inner block is executed.
Example
package com.tutorialspoint;
public class JavaTester {
public static void main(String args[]) {
int i = 0;
outer: {
inner :{
System.out.println("inner block ends");
i++;
if(i != 0) {
break outer;
}
}
System.out.println("outer block ends");
}
}
}
Output
inner block ends
java_basic_syntax.htm
Advertisements