While loop statements in Java

In previous article we have covered for loop here we will discuss about the other type of looping statement WHILE. WHILE statement is useful when you want to execute something till a particular condition is true.

Scenario of WHILE loop

Ask user to provide input and wait till user provide the input.

Syntax of WHILE loop

Here while statement will evaluate the expression and check if it is true or not. If true then execute the statement within loop. Once completed execution in loop again check the expression. Perform this activity unless value of expression is not TRUE.

Example Code WHILE loop

 

Output of above code would be

8 Comments While loop statements in Java

  1. Pingback: Java Beginners Tutorial for Loop statements in Java » Java Beginners Tutorial

  2. Amain

    Sir,
    I would like to confirm if body of the while loop gets executed if conditional test evaluates to true or false, because when i executed the code as given on this page ,the output was different than as given by you.Acc yo ur expalnation body of while loop gets executed if test is false ,rather it shud b true.Am i right?

    Reply
    1. Vivekanand Gautam

      Hi Amain,

      Example given in article is correct. As per your question block will get executed till condition is true. Moment it becomes false execution will come out of block.

      As flag was false in first time so it didn’t go inside block. I have changed the code block so that you can understand clearly.

      Please check it again.

      Thanks

      Reply
  3. Amain

    Sir,
    I suppose you have changed the code . Thank you for that. But I suppose that the explanation that you have given in the code in form of the comments also needs to be changed and sir I suppose the first line of the explanation is wrong if I am not wrong.

    /*
    * Here while will check the expression. value is “false” so statement
    * within loop will get executed.

    It was this statement I was talking about which seems wrong to me. As i have quoted “false” should be replaced with “true”.

    Reply
  4. aditya vardhan

    Need correction:
    Error:Here while statement will evaluate the expression and check if it is true or not. If NOT then execute the statement within loop
    Correct:Here while statement will evaluate the expression and check if it is true or not. If TRUE then execute the statement within loop

    Reply
  5. Anon

    This site is stupid, basic algorithmic stuff like while loops is at the end, but advanced topics like objects are put in the beginning….. How does one expect people to learn from that.

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *