Thursday, January 31, 2013

Understanding Java - while Loop

While Loop

It executes a code block while the Boolean expression remains true. 

Syntax :   while ( booleanExpression ) {
                          code block

Points to Ponder :
  1. Variable used in the Boolean expression must be initialized before the while statement.
  2. There must be valid condition test to stop, otherwise it becomes an infinite loop
  3. There must be a statement in the loop to modify the variable which controls the condition

'n' is a local variable and hence needs explicit initialization. Java compiler flags an error.

'n' needs to be initialized. Here is the second code( Example of Inifinite Loop )

Due to no change in the value of variable 'n',  it keeps printing 1.

Proper while Loop Example :

Any boolean value true can be used instead of boolean expression. If true is used in while, it behaves as infinite loop. To stop this loop, break statement can be used.

Now here is something very special about the nature of while

Java compiler does not allow the use of false literal in the condition/boolean expression. A smart compiler :). It flags a compile time error "unreachable code".  But here is something more wonderful about Java compiler.

Variable with value false is allowed... :)