Topics Index

Simulate Go To using break - Java Example Program

Simulate Go To using break
class GoToUsingBreak
    public static void main(String arg[])
        boolean t = true;
                    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

Before the break
After second block - inside first block
After first block


Here 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

  • Remove the break statement at LINE A to print the statements in third and second block.
  • Try the below code.
    for (int i = 0; i < 5; i++)
        outer :
            inner :
                System.out.println("Inside inner block");
            System.out.println("Inside outer block");
    Since we used break statement in outer block only the statements in inner and outer block will get executed and so the output of the above code will become as shown.
    Inside inner block
    Inside outer block

© meritcampus 2019

All Rights Reserved.

Open In App