Java do Keyword

Java do Keyword


Do Keyword In Java
While loop is used with do keyword and form a do-while loop.
While says: “repeat the statements in the body as long as
condition( ) returns true.” 
The sole difference between while and do-while is that the statement of the do-while always executes at least once, even if the expression evaluates to false the first time. In a while, if the conditional is false the first time the statement never executes. In practice, do-while is less common than while.
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.
  • Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression.
  • If this expression is true, the loop will repeat. Otherwise, the loop terminates.
  • The do-while loop is especially useful when you process a menu selection because you will usually want the body of a menu loop to execute at least once. Consider the following Example.
Now we will see Example - 
Example - 
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
Chapter 5: Control Statements 87
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}

 
Output - 
Help on:
1. if
2. switch
3. while
4. do-while
5. for
  Choose one:
4
The do-while:
do {
statement;
} while (condition);