label
is the name that identifies a block of code.
Simulate Go To using break
class GoToUsingBreak
{
public static void main(String arg[])
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the break"); // LINE A
if(t) break second; // break out of second block
System.out.println("This won't execute - inside third block - after break"); // LINE B
}
System.out.println("This won't execute - inside second block"); // LINE C
}
System.out.println("After second block - inside first block"); // LINE D
}
System.out.println("After first block"); // LINE E
}
}
OUTPUTBefore the break
After second block - inside first block
After first block
DESCRIPTIONHere first
, second
and third
are labels for various blocks. In the if condition, since t
is true
, break
is called on the label second
. So, the first statement after the second
block will be called. That statement is LINE D
, which prints After second block - inside first block
. After this LINE E
is called.
If break first;
is called instead of break second;
then the execution directly goes to LINE E
without executing LINE D
THINGS TO TRY
- Remove the
break
statement at LINE A
to print the statements in third and second block.