While And Do While In JAVA With Examples – Complete Tutorials

The While is a type of loop which evaluate the condition first. If condition evaluate to true the code inside the block{} will be executed and if it evaluate to false it will jump outside the while loop. The While in JAVA has two parts, first defining a Boolean expression inside parenthesis which will be tested and second is a statement or code which will be executed continually until Boolean expression evaluate to be true.


Syntax Of While:

The syntax of While in JAVA is:

initialize-value;
while(Boolean-Expression){
statement-or-code; //This will be executed continually until Boolean expression evaluate to true
increment-decrement-value;
}

initialize-value – First initialize the value first before starting while loop. Boolean-Expression – Boolean expression will be evaluated. If it comes out to be true then code inside it will executed otherwise compiler jumps outside the loop. statement-or-code – The code that you want to execute after Boolean expression evaluate to true. increment-decrement-value – increment or decrement the value of initialized variable


Examples Of While In JAVA:

Lets create a simple program to print 1 to 10 number using While loop:

public class WhileExample {

	public static void main(String[] args) {
		
		int i=1;
		while(i<=10){
		System.out.println(i);
		i++;
		}

	}

}

Output:

1
2
3
4
5
6
7
8
9
10

Do While In JAVA:

The Do While loop will first execute the code inside do{} and then evaluate the while Boolean expression. The statements will continue to execute until Boolean expression evaluate to false. In do while, we first put statement or code that we want to execute inside the do block and then we put the Boolean expression inside While parenthesis just outside do block.

Important Note: The major difference between While and do While is that statement will be executed atleast once in do while.


Examples Of Do While In JAVA:

We can create the same program to print 1 to 10 number with do while in JAVA:

public class DoWhileExample {

	public static void main(String[] args) {
		
		int i=1;
		do{
		System.out.println(i);
		i++;
		} while(i<=10);

	}

}

Output:

1
2
3
4
5
6
7
8
9
10

Ask Your Question Or Leave A Reply

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