Sunday, August 15, 2010

Using Break as GOTO

Break statement has following three uses:-

1.Terminate the execution sequence in switch.
2.Used to exit loops from anywhere.
3.Break used as form of GOTO.

GOTO statement as we know is not supported by Java.The reason being it provides control branching in unstructured and arbitrary manner.It is quite obvious from a C and C++ program that after reading through GOTO-ridden code is hard to understand the flow of program and also code is hard to maintain.GOTO also affects our performance considerations and compiler optimization.Indeed there are situations where GOTO is useful like if you are gone very deep inside loops then it would be easy to come out of those loops.

Using this form of break ,you can break out of n number of blocks.In this form of break we can also specify that where execution will resume.Since this version of break uses labels we specify labels after break like below:

break label ;

label identifies a block of code where we want to take our program control.

NOTE:-The program control resumes execution after the end of labelled block for example look at following :-

Class TestBreakGoto{
public static void main(String a[]){
int i=0;
first:{
second : {
third : {
System.out.println("Started execution ");
if(i==0)
break second;
System.out.println("Exit Third");
}
System.out.println("Exit second");
}
System.out.prinltn("Out of second");
}
}
}

One important rule for break as GOTO is the labelled break statement must be inside the label block.That is look in above example we have three labels first,second and third.We can goto any label unit our break inside the innermost label otherwise it will give undefined label error.And also you must use higher blocks label to break from inner block.Otherwise the previously mentioned error will be encountered.

Useful Links:-

do-while loop
The while loop
if-else construct
The switch construct
Java Break Statement

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey(Read More about him) .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP