Iteration – For, While, do-while in Java

Let us start with the topic of iterations in Java. Before moving to the technical terms, let us first understand what Iteration is.

Iteration in general sense means Repetition.

Let’s move down the memory lane to the high school times. If you’re reading this, I can guarantee that most of you had been either punished by your teacher with the task of writing 500 times ‘ I will not talk in the class’ or might have witnessed your friends doing the same.

Now if you have faced the punishment, you would have definitely wished for a gadget or something that would have done this in a go.

Similarly imagine you are supposed to do the same thing on a computer as well, like printing 30 times ‘StudyMite’ using Java programming.

The code would be nothing but writing the following statement 30 times in a Java Editor:

System.out.println(“StudyMite”);

It will be indeed a hectic and monotonous task to be performed.

This is why the idea of looping constructs and iterations are introduced.

Structure of a Looping Construct:

  • Control Variable: A variable which has an initial value and determines the duration of repetition is called Control Variable. It is also known as Initial Value.
  • The body of the Loop: The set of statements which are executed within the looping construct continuously.
  • Test Condition: Each looping construct contains a test condition which is verified at each iteration of the loop. The loop is executed till the test condition is true, otherwise, it immediately terminates.
  • Step Value: The step value updates the control variable unless the test condition is false.

On the basis of the nature of iterations, loops can be classified into:

Fixed Iterations:

In this type of looping structure, the statements are repeated for a fixed number of times. The loop terminates after executing the block of statements within the loop construct for the said number of times.

  1. For Loop

Variable Iterations:

Loops with varying iterations in which the number of times the loop is going to be executed is not fixed are called Variable Iterations.

  1. While Loop

  2. do-While Loop

 

Iteration – For, While, do-while in Java