While Loop
While loop executes a code block while the Boolean expression remains
true.
Syntax: while (
booleanExpression ) {
code block
}
Points to Ponder :
- The Variable used in the Boolean expression must be initialized before the while statement.
- There must be a valid condition test to stop, otherwise, it becomes an infinite loop.
- There must be a statement in the loop to modify the variable that 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 Infinite Loop )
Due to no change in the value of the variable 'n', it keeps printing 1.
Proper While Loop Example :
A boolean value can be used instead of a boolean expression. If true is used in a while loop, it behaves as an infinite loop. To stop this loop, the 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 the Java compiler.
Variable with value false is allowed... :)