Menu
Topics Index
...
`


Control Statements > Jump Statements >
Siva Nookala - 15 Mar 2016
Java does not support goto to avoid complex code. When we use lots of goto's it will be very difficult to understand that code. break when used with label's can be a substitute for goto.

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
    
    }
}
OUTPUT

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

DESCRIPTION

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

THINGS TO TRY
  • 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");
            break;
        }
    }
    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

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.