![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Do while loop is aexit controlled
loop. That is the condition is checked at the end of the loop thats why if condition does not satisfy , the loop statements are executed at least once.
Do while loop mostly used in the menu driven programs like to display the MENU to user again and again until exit button is pressed.
do { // body of do while loop // increment or decrement } while(condition);
Following programs will clear the exact difference between while loop and do-while loop.
public class Test { public static void main(String[] args) { String msg = "Androidberry"; while(msg.equals("Java")) { System.out.println("Hello There"); } } }
No output - Because while loop is not executed.
public class Test { public static void main(String[] args) { String msg = "Androidberry"; do { System.out.println("Hello There"); }while(msg.equals("Java")); } }
In real life programming, we don't know when the user will stop providing values to the computer. In that situation we can use do-while loop for executing certain period time.
import java.util.Scanner; public class Test { public static void main(String[] args) { int length,choice=0; String str; Scanner sc = new Scanner(System.in); do { System.out.println("Enter string : "); str = sc.next(); length = str.length(); System.out.println("Length of String is : "+length); System.out.println("Do want to try another string? (1 = Yes| 2= No) : "); choice = sc.nextInt(); }while(choice !=2); } }