Difference between while and do-while loop with example in java









Difference between while and do-while loop in java



while loop
do-while loop
in while loop statements may not be executed even once.

booleanVal is evaluated at top in while loop.
So, Statements inside while loop are executed when booleanVal is true.

If booleanVal evaluates to false in first loop/evaluation, then while loop statements will not be executed even once.

in do-while loop statements are at least executed once.

First statements inside do block are executed, then booleanVal is evaluated.
Program - When while loop statements are not executed even once.


/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 3;
          while(i < 3){
                 System.out.println("i= " + i);
                 i++;
          }
   }
}
/* OUTPUT
*/
Program - Even with same while condition used in do-while, do-while loop statements are at least executed once (as compared to while loop program).

/** JavaMadeSoEasy.com */
public class LoopTest {
   public static void main(String[] args) {
          int i = 3;
          do{
                 System.out.println("i= " + i);
                 i++;
          }while(i < 3);
  
   }
}
/* OUTPUT
i= 3
*/



Must read for you :
Must read for you :

No comments:

Post a Comment