There are several looping statements available in java. One of them is do while loop
in java.
While loop is used to execute some statements repeatedly until the condition returns false
. If the number of iterations is not known beforehand, while the loop is recommended.
In Do while loop, loop body is executed at least once
because condition is checked after loop body.
Syntax for do while loop in java
1 2 3 4 5 |
do{ //block of statements }while(condition) |
Let’s take a very simple example:
Print number from 1 to 10 using while loop
1 2 3 4 5 6 7 8 9 10 11 12 |
package org.arpit.java2blog; public class DoWhileLoopMain { public static void main(String[] args) { int i=1; do { System.out.print(" "+i); i++; }while(i<11); } } |
Output:
Let’s try to print only even numbers now.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class DoWhileLoopMain { public static void main(String[] args) { int i=1; do { if(i%2==0) System.out.print(" "+i); i++; }while(i<11); } } |
Output:
Exercise
If you are given array of integer, you need to find an element in that array.
Input:
{32,45,53,65,43,23}
You need to write a program to search an element in the array.If element is found in the array, return "PRESENT" else return "NOT PRESENT"
I would recommend you to try it yourself and then look at below code.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package org.arpit.java2blog; public class DoWhileLoopMain { public static void main(String[] args) { DoWhileLoopMain dwl=new DoWhileLoopMain(); int arr[] ={32,45,53,65,43,23}; System.out.println(dwl.findElementInArr(arr, 53)); } public String findElementInArr(int arr[],int elementTobeFound) { int i=0; do { if(arr[i]==elementTobeFound) { System.out.println(elementTobeFound+" is present in the array "); return "PRESENT"; } i++; }while(i<arr.length); return "NOT PRESENT"; } } |
Output:
PRESENT
Infinite do while loop in java
You need to be careful with the condition you provide in for loop otherwise you may end up creating infinite for loop.
For example:
Let’s say you want to print number from 10 to 1 and you use below code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class DoWhileLoopMain { public static void main(String[] args) { int i=10; do { System.out.print(" "+i); i--; }while(i>0) } } |
Output:
Now in above code, instead of i–, you have put i++. In this code, the loop will go into infinite loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class DoWhileLoopMain { public static void main(String[] args) { int i=10; do { System.out.print(" "+i); i++; }while(i>0) } } |
Another example of infinite loop is below code:
1 2 3 4 5 6 7 8 9 10 11 |
package org.arpit.java2blog; package org.arpit.java2blog; public class WhileLoopMain { public static void main(String[] args) { do{ }while(true) } } |
That’s all about do while loop in java.