Loops in Java – Types and Examples of Looping in Java

1. Objective

In our last chapter, we have completed Access Modifiers in java. Here, we will talk about Loops in Java and different types of loops in Java language with Java syntax, uses, and scope.

So, let’s start Java Loops.

Loops in Java - Types and Examples of Looping in Java

Loops in Java – Types and Examples of Looping in Java

2. What are Loops in Java

Java is Multi-featured language, loops in Java are a way to run a particular instruction or java function a number of times if, this is done after every iteration.

Java has 3 ways of executing the loops, they are all nearly similar, with some syntax and condition checking differences.

Do you know about Java For Loop?

3. Types of Java Loops

a. While loop in Java

In Java, while loop, a loop is continuously executed if the Boolean condition comes true, it can be considered as a repeating if statement.

Loops in Java - While loop

Loops in Java – While loop

The syntax of Java While Loop

while (boolean condition)
       {
            loop statements...
       }

While loop is an entry controlled loop, i.e. the condition is tested before the loop.

The condition is tested and the iteration follows until the condition becomes false, and that marks the end of the loop.
Example

// Java program to illustrate while loop
class whileLoopDemo
{
    public static void main(String args[])
      {
        	int x = 1;
        	// Exit when x becomes greater than 4
       		 while (x <= 4)
        	{
         		  System.out.println("Value of x:" + x);
         	         //increment the value of x for next iteration
         	         x++;
                }
       }
}

Output 
Value of x:1
Value of x:2
Value of x:3
Value of x:4

Read about Switch Statement and Switch Case in Java

b. For loop in Java

Java for loop is a concise version of while loop, it provides the user to write the whole condition, i.e. initialization, condition and Increment/decrement in one line.
Syntax of Java for loop

 for (initialization condition; testing condition;
  increment/decrement)
{
    statement(s)
}

A for loop in java is also an entry controlled loop, we first initialize the variables in use and then the condition is tested, and accordingly, increment or decrement takes place.

Loops in Java - For Loop

Loops in Java – For Loop

Example 

// Java program to illustrate for loop
class forLoopDemo
{
    public static void main(String args[])
    {
        // for loop begins when x=2
        // and runs till x <=4
        for (int x = 2; x <= 4; x++)
        System.out.println("Value of x:" + x);
    }
}

Output 
Value of x:2
Value of x:3
Value of x:4

Enhanced for loop

This version was introduced in Java 5, this feature allows you to iterate with elements of arrays. This feature should only be used when the index is unknown.
Syntax 

for (T element:Collection obj/array)
{
    statement(s)
}

Example of enhanced for loop in Java

// Java program to illustrate enhanced for loop
public class enhancedforloop
{
    public static void main(String args[])
    {
        	  String array[] = {"Ron", "Harry", "Hermoine"};
       		 //enhanced for loop
       		 for (String x:array)
       		 {
            		System.out.println(x);
       		 }
       			 /*for loop for same function
       			 for (int i = 0; i < array.length; i++)
       		 {
           		 System.out.println(array[i]);
       		 }
       */
    }
}

Output 
Ron
Harry
Hermoine

Have you known about the Island of Isolation in Java?

c. do while loop in Java

A do while statement is an exit controlled loop, i.e. it checks the condition after the execution of the loop.
Syntax

do
{
    statements..
}
while (condition);
Loops in Java - Do While Loop

Loops in Java – Do While Loop

Example of do while loop  in Java

// Java program to illustrate do-while loop
class dowhileloopDemo
{
    public static void main(String args[])
    {
        int x = 21;
        do
        {
            //The line while be printer even
            //if the condition is false
            System.out.println("Value of x:" + x);
            x++;
        }
        while (x < 20);
    }

Output
Value of x: 21

Java Quiz

4. Pitfalls in Loops in Java

a. Infinite loop

This loop takes place when the condition for some reason fails.
Example

//Java program to illustrate various pitfalls.
public class LooppitfallsDemo
{
    public static void main(String[] args)
    {
        // infinite loop because condition is not apt
        // condition should have been i>0.
        for (int i = 5; i != 0; i -= 2)
       {
            System.out.println(i);
        }
        int x = 5;
        // infinite loop because update statement
        // is not provided.
        while (x == 5)
        {
            System.out.println("fail");
        }
   }
}

Follow this Link to know about Decision Making in Java

b. Shortage of memory

This happens when there is a continuous addition in the loop but there occurs a shortage of memory.
Example 

//Java program for out of memory exception.
import java.util.ArrayList;
public class Integer1
{
    public static void main(String[] args)
    {
        ArrayList<Integer> ar = new ArrayList<>();
        for (int i = 0; i < Integer.MAX_VALUE; i++)
        {
            ar.add(i);
        }
    }
}

Output 

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

at java.util.Arrays.copyOf(Unknown Source)

at java.util.Arrays.copyOf(Unknown Source)

at java.util.ArrayList.grow(Unknown Source)

at java.util.ArrayList.ensureCapacityInternal(Unknown Source)

at java.util.ArrayList.add(Unknown Source)

at article.Integer1.main(Integer1.java:9)

So, this was all about Loops in Java. Hope you like our explanation.

5. Conclusion

In this tutorial for loops in java we learned about the loops, their Java syntax and their usage in programs. We also learned some of the features related to them. This will help us to write and understand the more complex programs easily.

Related Topic – Java String, Methods And Constructor

For reference

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.