Monday, September 28, 2015

Using break as a Form of Goto

In addition to its uses with the switch statement and loops the break statement can also be employed by itself to provide a“civilized” form of the goto statement.
Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner.
This usually makes goto-ridden code hard to understand and hard to maintain. It also prohibits certain compiler optimizations. There are, however, a few places where the goto is a valuable and legitimate construct for flow control.
For example, the goto can be useful when you are exiting from a deeply nested set of loops. To handle such situations, Java defines an expanded form of the break statement. By using this form of break you can, for example break out of one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any block.
Further, you can specify precisely where execution will resume, because this form
of break works with a label. As you will see, break gives you the benefits of a goto without its problems.
The general form of the labeled break statement is shown here:
break label;
Most often, label is the name of a label that identifies a block of code. This can be a stand-alone block of code but it can also be a block that is the target of another statement.
When this form of break executes, control is transferred out of the named block. The labeled block must enclose the break statement, but it does not need to be the immediately enclosing block.
for example, that you can use a labeled break statement to exit from a set of nested blocks. But you cannot use break to transfer control out of a block that does not enclose the break statement.
To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon. Once you have labeled a block, you can then use this label as the target of a break statement. Doing so causes execution to resume at the end of the labeled block.
// Using break as a civilized form of goto.
class WLGoto
{
public static void main(String args[])
{
boolean chk = true;
one:
{
System.out.println("In First");
two:
{
System.out.println("In Second.");
if(chk)
break one; // break out of second block
System.out.println("In Second Block Condition False");
}
System.out.println("This is First block.");
}
System.out.println("Program End.");
}
}

Type following command in command prompt

javac WLGoto.java
java WLGoto
 
In First
In Second.
Program End.

No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)