Menu
Topics Index
...
`


Control Statements > Iteration statements (Loops) >
Siva Nookala - 23 Aug 2016
do-while loop is similar to while loop statement but do-while loop executes all the statements in the block, at least once and then checks the condition at the end. If the condition is true then all the statements are re-executed. This checking of the condition and execution of the statements/blocks continues until the condition is false.
The Syntax for do-while loop in Java is below;

do {
// body of loop
} while (condition);

  • Here the condition is a boolean expression, which should return either true or false.
  • We should always terminate do-while statement with semicolon(;). This is unlike for and while where we need not put semicolon at the end.
  • Each iteration of the do-while loop first executes the body of the loop and then evaluates the condition.
do while loop in java,do while,do while loop,do while loop in Java, do while in Java,while loop,example for do while loop in java,java do while,do while java

Do While Demo
class DoWhileDemo
{
    public static void main(String arg[])
    {
        int x = 1;
        do
        {
            System.out.println("The x value is: " + x);
            x++;
        } while( x <= 3 ); // LINE A
    }
}
OUTPUT

The x value is: 1
The x value is: 2
The x value is: 3

DESCRIPTION

Here the x is initialized to 1. Now the control enters the do block and prints the x value as The x value is: 1 then, it increments the x value by 1. So x becomes 2. Then it checks for the condition 2 <= 3 which is true, so it prints The x value is: 2 and repeats the same. Next it prints The x value is: 3, then x value will become 4 so the condition 4 <= 3 will become false causing the loop to terminate.

THINGS TO TRY
  • Remove the semicolon at LINE A. It should give a compilation Error.
  • Print the numbers which are divisible by 3 between 3 to 30.
  • Print the numbers which are divisible by 2 between 40 to 60.
The difference between do-while loop in Java and while-loop is that do-while loop in Java evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are executed at least once.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.