Java do...while Loop

The do...while loop is similar to while loop with one key difference. The body of do...while loop is executed for once before the test expression is checked. Here is the syntax of the do...while loop.


\begin{lstlisting}
do {
// codes inside body of do while loop
} while (testExpression);
\end{lstlisting}

The body of do...while loop is executed once (before checking the test expression). Only then, the test expression is checked. If the test expression is evaluated to true, codes inside the body of the loop are executed, and the test expression is evaluated again. This process goes on until the test expression is evaluated to false. When the test expression is false, the do...while loop terminates.

The following program calculates the sum of numbers entered by the user until user enters 0. To take input from the user, we have used the Scanner object. To learn more about Scanner, visit Java Scanner.


\begin{lstlisting}
import java.util.Scanner;
\par
class Sum {
public static voi...
...test expression
\par
System.out.println(''Sum = '' + sum);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Enter a number: 2.5
Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0
\end{lstlisting}



Subsections