- by Rutu Shah
In previous tutorial, we saw about for loop, enhanced for loop and while loop, and in this tutorial we will learn about do-while loop in java.
Do-while loop is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.
Syntax
do{
//block of code to execute the statements
}while(condition);
In do-while loop we execute the statements first, and there is no checking of condition for the first time.
After the execution of the code block, the condition is checked for a true or false value. If it is evaluated to true, the next iteration of the loop starts and continuous until a condition becomes false.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
Note: In the do-while loop, we need to execute the statements at least once before any condition is checked, and therefore is an example of an exit control loop.
Example 1
You can find the code here
package com.qacaffe.examples.loops;
public class DoWhile1 {
public static void main(String[] args) {
System.out.println("Example of do-while Loop.");
int j = 1;
do {
System.out.println(j);
j++;
} while (j < 10);
}
}
/*
Output:
Example of do-while Loop.
1
2
3
4
5
6
7
8
9
*/
Example 2
You can find the code here
package com.qacaffe.examples.loops;
import java.util.Scanner;
public class DoWhile2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number from where you want to print digits in reverse order : ");
int digit = scanner.nextInt();
do {
System.out.println(digit);
digit--;
} while (digit >= 1);
}
}
/*
Output:
Enter a number from where you want to print digits in reverse order : 5
5
4
3
2
1
*/
Example 3
package com.qacaffe.examples.loops;
public class DoWhile3 {
public static void main(String[] args) {
//Variable declaration section
String array1[] = {"Mike", "Jason", "Leonard", "Shane"};
int array2[] = {1, 3, 4, 5, 7, 9};
int count = 0, c2 = 0;
//do while loop logic for accessing string elements from the array
System.out.println("-----Printing String array elements : ");
do {
System.out.println(array1[count]);
count++;
} while (count < array1.length);
//do while loop logic for accessing integer elements from the array
System.out.println("-----Printing Integer array elements : ");
do {
System.out.println(array2[c2]);
c2++;
} while (c2 < array1.length);
}
}
/*
Output:
-----Printing String array elements :
Mike
Jason
Leonard
Shane
-----Printing Integer array elements :
1
3
4
5
*/