Loops in Java

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

A sequence of statements are executed until a specified/Given condition is true, or the loop is broken using the break statement

This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body; if there only one statement, then we can write without {}.

After every execution of the loop body, the condition is verified, and if it is found to be true, then the loop body is executed again.

When the condition check returns false, the loop body is not executed.

There are Three types of Loops in Java:

  • While
  • do-While
  • for

Depending on the position of control statement in the loop, the control structure may be classified as either entry controlled loop or exit controlled loop.

For and while loops are entry controlled loop because the condition is checked on the entry and do-while loop is an exit controlled loops the condition is checked at the end of the loop.

While Loop in Java

You use the keyword while, then a condition enclosed in parentheses, then a single statement, which is the thing which gets repeated as long as the condition is true.

while (condition) {
// execute only if condition is true
...
}

If the body of the loop has to be more than one statement, enclose it in the curly brackets {}. This creates a compound statement, and the while will treat it as a single statement.

The condition can be any expression, from a single variable or constant, through a complex sequence of logical operators. Just be sure that condition evaluates to the boolean values true or false, or the compiler will signal a type error.

Java is different from C, In C any non-zero integer value is considered true but Java throws an error for it. So Java will not consider the numbers in place of the condition

public class WhileLoop {
    public static void main(String[] args) {
        int i = 0;
        while(i<10){
            System.out.println(i);
            i++; // i= i+1
        }
    }
}

while-loop-java

do-while loop in Java

In a do…while loop, the statements in the body of the loop are executed once before the condition governing the loop is tested.

do-while-loop

If the condition evaluates to true, the loop will iterate a second time executing the loop’s body again; otherwise, the loop exists because the condition has become false.

do{
   //statements
} while (condition)

As for a real-world example of this, consider the input of a PIN number when using a cash dispenser. The PIN must be entered once before testing so a do…while loop is a perfect choice, i.e.

public class DoWhile {
    public static void main(String[] args) {
        int actualPIN = 1212;
        int attempts = 0;
        int pin;
        do{
            System.out.println("Enter your pin : ");
            Scanner in=new Scanner(System.in);
            pin = in.nextInt();
            attempts++;  // number of attempts
        }while(pin != actualPIN && attempts<3);
    }
}

Where the loop will iterate a maximum of three times to allow entry of a valid PIN number, a while loop could also be used here.

So what is the difference? It merely depends upon whether the algorithm requires that the body of the loop needs to run once first before deciding whether the loop will continue. If so, use a do…while loop, otherwise you should use a while loop.

int i = 0;
do{
    System.out.println(i);
}while(i>10); // result false

For Loop in java

The for loop provides a mechanism to repeat a task until a particular condition is true. The for loop has three expressions; semicolons are used for separating these expressions.

for(initialization_expr; test_expr; update_expr)
{
  /* body of the loop */
  // Statement Block;
}
  • The initialization expression is evaluated. It is typically used to initialize a counter or other variable that must have a starting value. This is the first action performed by the loop, and it is only done once.
  • The test expression is evaluated. The test expression is a relational expression that determines the number of the iterations desired or the condition to exit the loop. If this evaluates to false, then the loop terminates immediately. If this evaluates to true, then the statement block is executed.
  • After the statement block is executed, the update expression is evaluated. It executes at the end of each iteration. Typically, this expression is used to increment or decrement the variables declared in the initialization expression. After the update expression has been evaluated, the loop returns to step 2.
Example with Explanation:
for (num = 1; num <= 5; num++)
  • is the classic c like loop, and has a few parts...
  • The num=1 is run just once, no matter what, as a first action.
  • The num++ is run each time the loop goes around, just after the instructions in the main body of the loop
  • The num<=5 is evaluated only after that, and should return true if the loop should keep going around, and false to break out of the loop.
  • So, why is num equal to 6 after the loop has run? Well, the loop would have continued if it was 5 or below, it started as 1, and was only ever incremented.
  • The key point you may be confused by, and the slight weirdness in this syntax is that even though the num++ is written after the num<=5, it is effectively evaluated just beforehand, after the main body of the for loop.

For Each loop in java

for each loop is mainly used to traverse array or collection elements. The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

for-each loop removes the dependency of the condition and loop variable, and it's increment/decrement. We can make the for-each loop by declaring the variable out and incrementing decrementing the variable along with break statement

Syntax :

for(type variable  : Collection/array)
{
     System.out.println(i);
}
How does the for-each loop work?
public static void main(String args[])  
{ 
    int arrayA[]={1,2,3,4,5}; 
    for(int item : arrayA)
    { 
         System.out.println(i); 
    } 
}

Here's how the enhanced for loop works. For each iteration, for-each loop

  • iterates through each item in the given collection or array (collection),
  • stores each item in a variable (item)
  • and executes the body of the loop.

Infinite Loops

Infinite loop means a loop that never ends. In this tutorial, I will show you how to write an infinite loop in Java using for and while loop.

While loop to write an infinite loop :

while loop first checks a condition and then runs the code inside its block. We can make it an infinite loop by making the condition true

while(true){
    System.out.println("printing...");
}
for loop to write an infinite loop

If we skip the three parts of the for loop then for loop becomes an infinite loop. (the second way)The important part is the condition if we skip it for loop becomes an infinite loop

for(;;){
    print("printing...");
}
Do-While loops as Infinite loop

Make the condition as true instead of some relational operations then do-while loop also becomes infinite.

do {  // The do/while in infinite loop.
    … stuff …
  } while ( … some condition … );
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions