Wednesday, April 15, 2009

The While Loop

The while looping construct

The while loop is Java's most basic and fundamental looping statement.It continuously repeats the statement or some block of expression while its controlling expression is true.This controlling expression is of Boolean form that is it may either return true or false.The basic syntax is:-

while(Condition)
{
//statements or block of statements
}

As I said earlier the condition is a Boolean expression.The code inside loop will be executed as long as the condition is true.When condition becomes false the loop terminates and control returns to the very next line of code following the loop.

Consider following example:-

int i=0;
while(i < 5)
{
i++;
System.out.println("Loop completes :"+i+"times");

}

If you will run that code snippet you will get output something like following

Loop completes :1 times
Loop completes :2 times
Loop completes :3 times
Loop completes :4 times
Loop completes :5 times

Any Boolean expression can be placed in place of condition.
If you are executing only one statement the curly braces are unnecessary.

Explanation:-We initialized a variable i as 0.It is checked in the while as if it is less than 5 or not since it returns a Boolean value and at first it returns true thus code inside curly braces is executed until the value of i reach 5.When it will reach 5 then in next iteration the loop will terminate.

NOTE:-
1.Since Java evaluates the conditional expression at the very start so there is no chance that loop may execute once.We will see further how once loop is executed using do-while construct.

2.The body of a while loop can be empty.That is no statements inside loop body:
example:-
//this is an empty while loop
while(i++
In professionally written java code,programmers often code short loops without body,where most of work is done in controlling expression itself.So try to match it but at very basic level use it as suits you once you mastered it go for professional writing.

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