JAVA BEGINNERS TUTORIAL – Loops

sometimes we need to execute a block of code in several recurrent times. this action called a loop and for this action Java have some Loop statments as the following:

while Loop:

A while loop is a control structure that allows you to repeat a task a certain number of times. and it means while an expression is true do the action in the block code and do it again and again till the expression result is false.

Syntax:

Example:

do-while Loop:

do-while loop is similar to a while loop, but do-while loop execute the code blockat least one time. If the expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the expression is false.

Syntax:

Example:

for Loop:

for loop is a most used loop in any application. A for loop is useful when you know how many times a task is to be repeated. Here is the flow of control in a for loop:

  • The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
  • Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.
  • After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.
  • The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.

Syntax:

Example:

The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read:

Syntax:

The syntax of enhanced for loop is:

  • Declaration: The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
  • Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example: