Saturday, August 14, 2010

Java Break statement || using break to exit a loop

Java Provides 3 ways by which we can use the break statement:-

1.It terminates switch statement
2.It can be used to exit loop
3.It can also be used as GOTO statement.

Here we will learn about break statement used to exit a loop.

Using break statement we can force the loop to terminate immediately ,bypassing all the conditional expressions and the execution resumes just after the next line following loop body.In other words we can say when a break statement is encountered inside the loop,the loop terminates immediately and program control resumes at the next statement following the loop.This concept would be more clear by understanding following example:-

class Looptest
{
public static void main(String a[])
{
for(int i=0;i<10;i++)
{
if(i==5)
break;//terminated the loop after 5 iterations
System.out.println("i= "+i);
}
System.out.println("Loop complete after 5 iterations");
}
}

The output of above is as expected 5 completed iterations

i= 0
i= 1
i= 2
i= 3
i= 4
Loop complete after 5 iterations

As evident above in the example our for loop is designed to run 10 times but since during execution after 5 iterations the interpreter encounters break statement thus it exited current loop immediately and gives us output as above.Last statement in output indicates that loop executed successfully.There can be many uses of break like if we are running an infinite loop then if we wish to terminate loop at some point the it could be used .Also we can intentionally terminate the loop when some condition is satisfied.

NOTE:-break statement can be used with any kind of loop be it a FOR LOOP,WHILE LOOP,DO WHILE LOOP.

In case of nested loops the functionality remains same as for a single loop.That is if we put break in inner loop then the program control would be transferred to outer loop upon encountering the break statement.The point to remember is by placing break inside inner loop does not exit from all loops rather it transfers control to outer loop.

Useful Links:-

The while loop

The do-while loop

if-else statement

if-else-if statement

The switch construct

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