Loops in Java

Sometimes we may need to execute our code multiple times to get our result. In that case, we can write same code multiple times but that is not the correct solution. We have loops in java to execute same piece of code multiple times.

Loop simply means repetition. We can write our program inside loop block and give some conditions to keep executing till we get what we want.

Suppose we have to print our name 10 times, then we can write System.out.println("My Name"); 10 times. But that only makes our program more longer. With the help of looping, we can print same syntax not only 10 times but how much we want in much sorter code.


Looping Terminologies

Before starting anything, lets know some terminologies we will be using.

  • Initialization: In simple words, Iteration means starting value. This is same as we used to assign data to variables. Example: int i = 0;

  • Condition: As we already read decision making, we don't have to elaborate more understanding condition. It is same as it was in decision making. It gives us true or false result with the help of relational operators. Example: a > b;

  • Post-operation: Post operation means some code that executes after executing program inside loop block. We will use increment or decrement mostly, however we can use any operation we want. These operations are usually done with iteration variable. Example: i++;

  • Iteration: Iteration is the repetition of a process in order to generate a sequence of outcomes. The sequence will approach some end point or end value. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration.


Types of Loops:

  • For Loop
  • While Loop
  • Do While Loop

We will read all loops in detail now.


Switch Case in Java Previous Next For Loop in Java