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... :)
Useful post for beginners in java.
ReplyDeleteJava training chennai
Useful post!
ReplyDelete
ReplyDeleteThanks for sharing, I will bookmark and be back again
JAVA Training in Chennai
Hi I am Victoria lives in Chennai. I am a technology freak. Recently I did Java Course in Chennai at a leading Java Training Institutes in Chennai. This is really helpful for me to make a bright career in IT industry.
ReplyDeleteHi, I am Vijay from Chennai. I am technology freak. I did Android mobile application development course at Fita academy, this is very useful for me to make a bright career in IT industry. So If you looking for best Android Training Institutes in Chennai please visit fita academy.
ReplyDeleteRegards..
Android Training in Chennai