i

JAVA Complete Course

Looping Statements

Looping statement we have already mentioned when we were running example of arrays. Looping statements help to run block of code several times. It means the same code will be executed multiple times. These are also called Iteration statements.

For statement executes the code until condition is false. It is used when number of iterations are known.

Code example:

Output will be:

There is another looping statement: while, which runs until the conditional statement will be false. Syntax of while loop statement looks like this:

Let’s revisit the actual example to understand it properly:

Output of the code will be following:

There is another looping statement which in practice is used rarely and only in specific cases, but let’s touch it very shortly. It is called do-while and even the condition is false, the block of while runs at least once. When we are using for or while, then it will execute the loop body only if the condition is true. In do-while loop, first loop block will be executed and then condition will be checked. So, it will execute the loop at least once. It is called exit controlled loop while for & while loop are called entry controlled loop.

As we mentioned there are also unconditional control statements. One of the example is break. It is actually the statement which is used in conditional statements to stop the execution of the block. Break is one of the Java keywords. It usually is used within any control statements in order to terminate the execution of the current loop or switch statements.

The output will be: