while loop in Java

In this post I will go through the basic syntax of while loop in Java. More info will follow in the video available on my YouTube channel.

So while loop does the same thing basically as for loop, but while is used when we cannot predict how many iterations will be executed. The syntax is as follows:

...
while(boolean condition){
code_to_execute
}

And as boolean_condition you specify the condition which will be evaluated each time before next iteration of the loop will be executed. As you can see, no control variable is used in clear way like in for loop.

Let’s consider the following for loop

for(int i = 0; i < 10; i++){
System.out.println(i);
}

The loop above could be re-written using while as follows

int i = 0;
while(i < 10){
System.out.println(i);
i++;
}

So the major difference is that any action we would like to make with the control variable should be done inside while loop. As well as control variable should be defined and assigned a value before while loop.

In the next post I will describe a do-while loop, which is slightly different from while. Stay turned!

Leave a Reply