While/do while

The while construct allows a program to loop for a number of times depending on some test. The difference between a simple while and a do-while can easily be overlooked. Essentially a while loop will execute zero or more times and a do-while loop will execute one or more times. If you think of the implicit logic the words do-while imply

"do this while something is true", indicating that the test will come after the loop has executed at least once. A while construct by contrast does the test before performing the first loop.

In actual Java code a while code looks like this

int i=1;
while(i <1){

The line i++ will add one to the variable i (also known as incrementing). This loop will execute zero times. The while test (i <1) will return false as 1 is not smaller than 1. The code will then continue executing after the closing brace.

The following code will however loop once and output the value of i to the console.

int i=1;

Last modified: Sunday, 20 September 2015, 07:21 PM