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... :)

8 comments:


  1. Thanks for sharing, I will bookmark and be back again




    JAVA Training in Chennai

    ReplyDelete
  2. 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.

    ReplyDelete
  3. Hi, This is Emi from Chennai. I have read your blog and I got some knowledge information. Really useful blog. Keep update your blog.

    Regards...
    Java Course in Chennai

    ReplyDelete
  4. Hi, 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.

    Regards..
    Android Training in Chennai

    ReplyDelete
  5. Hello Admin, thank you for the article. It has helped me during my Java training in Chennai. Fita academy is a Java training institutes in Chennai that provides training for interested students. So feel free to contact us to join our Java J2EE training institutes in Chennai.

    ReplyDelete