Showing posts with label while and do...while.. Show all posts
Showing posts with label while and do...while.. Show all posts

Java Loops - for, while and do...while

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
  • while Loop
  • do...while Loop
  • for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

The syntax of a while loop is:
while(Boolean_expression)
{
   //Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.