What is difference between while statement and do statement

What is difference between while statement and do statement ?

Answer : Difference between while and do-while is that while its expression to the top but do-while evaluates its expression at the bottom of the loop. So that, the while block first check condition then enters to the block but do block will be always executed at least once, please see test program below:

package com.javahonk.dowhiletest;

public class DoWhileTest {

    public static void main(String[] args) {
	int count = 1;
	// First it will check condition and won't print anything
	while (count < 1) {
	    System.out.println("Inside while count is: " + count);
	    count++;
	}

	// First time it will always execute and print 1
	do {
	    System.out.println("Inside do while count is: " + count);
	    count++;
	} while (count < 1);

    }

}

 

Output

What is difference between while statement and do statement

Leave a Reply

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