While Loop
It executes a code block while the Boolean expression remains
true.
Syntax : while (
booleanExpression ) {
code block
}
Points to Ponder :
- Variable used in the Boolean expression must be initialized before the while statement.
- There must be valid condition test to stop, otherwise it becomes an infinite loop
- 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... :)
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