do_while Loop

If we want execute loop body at least once, then we should go for do-while loop.
Syntax:

do{
Stmt1;
Stmt1;
.....
.....
stmtm;
}while(condition);
Stmtn;
  1. Statements in do-while loop are repeatedly executed as long as condition is true.
  2. Control goes out of loop, the moment condition is false.
  3. Statements outside the loop are executed,when condition is false.
  4. Semicolon (;) after the condition indicates end of do while loop.

Example:

class Test {

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

	}
}
/*
Output:
1
2
3
4
5
*/

Important Notes:

Curly braces are optional and without curly braces we are allowed to take only one statement between do and while,and that statement never be declarative statement.

class Test {

	public static void main(String[] args) {
		do
			System.out.println("hello");
		while (true);
	}
}
/*
Output:
hello
hello
hello
....
....
Infinity Loop.
*/

Example:

class Test {

	public static void main(String[] args) {
		do
		  int i=10;
		while(true);
	}
}
/*
Compiletime error.
*/

Example:

class Test {

	public static void main(String[] args) {
		do
		while(true);
	}
}
/*
Compiletime error.
*/

Example:

class Test {

	public static void main(String[] args) {
		do {
			System.out.println("hello");
		} while (true);
		System.out.println("hi");
	}
}
/*
Compile time error:
Unreachable code
*/