What Are Loops In Java?

What Are Loops In Java?
What Are Loops In Java?

Introduction

Loops, commonly known as iteration statements, are a type of control flow statement in a programming language. There are three types of control flow statements: sequential, conditional, and loop. 

The sequential instruction instructs the program to go from one instruction to another in a specific order. Based on some conditions, the conditional determines which instruction should be executed next. Iteration statements, on the other hand, allow program execution to repeat one or more statements.

Loops are undoubtedly an important feature of any program, and mastering the concept of controlled repetition is an important part of becoming a programmer.

Wondering how it actually works and reduces the repetitive work? Let’s walk through the most basic program of printing the first five Natural numbers:

Java Code Without Loop:

Tutorials point online IDE

In order to print numbers from 1 to 5 in a separate line. We have to write 5 print statements in the above code.

Java Code Using Loop:

For doing the same job here, we have used a simple loop and one print statement inside it.

Exciting, Isn’t it? Let’s get started with loops in the Java programming language!

Types of loops in Java

In the Java programming language, there are primarily four types of loops.

  • While loop
  • Do while loop
  • For loop
  • For each loop

We’ll explain them one by one.

While loop in Java

The most fundamental loop statement in Java is while. It repeats the execution of a statement or block while its controlling expression is true. 

Here’s how it looks in its most basic form:

while(condition) 
{
// body 
}

Any boolean expression can be used as the condition. Until the conditional expression is true, the code inside the loop will execute. When the condition becomes false, control is passed to the next line of code after the loop. 

Note: If only a single statement is inside the loop, the curly braces are not needed.

Program to demonstrate the while loop:

public class While 
{ 
public static void main(String args[]) 
	{ 
		int n = 5; 
		while(n > 0) 
		{ 
			System.out.println("Coding Ninjas " + n); n--; 
		} 
	} 
 
}

Output:
Coding Ninjas 5
Coding Ninjas 4
Coding Ninjas 3
Coding Ninjas 2
Coding Ninjas 1

 When we run the above program, it will print “Coding Ninjas” five times because n is 5. Some more important points about while loop are as follows:

  • The while loop evaluates its conditional at the start of the loop. If the condition is false initially, the loop’s body will not execute even once. 

For example, in the following code snippet, the call to print function is never executed.

int a = 10, b = 20; 
while(a > b) 
{
System.out.println("This will not be displayed");
}
  • The while loop (or any other Java loop) can have an empty body. Because in Java, a null statement (one that contains a semicolon) is syntactically valid. For example, consider the following program to find the midpoint between i and j.
class Test 
{ 
public static void main(String args[]) 
{ 
int i = 100, 
j = 200;

while(++i < --j) ; 
// no body in this loop S

System.out.println("Midpoint is " + i); 
} 
} 

Output:
Midpoint is 150

Here’s how the above program works:

  • The value of i is increased, whereas that of j is decreased. 
  • These values are then compared to one another. 
  • The loop repeats if the new value of i is still smaller than the new value of j
  • The loop ends if i is equal to or greater than j.  
  • In the end, i will hold a value that is halfway between the initial values of i and j when the loop ends.

Do while loop in Java

The do-while loop in Java is used to repeatedly iterate a portion of a program until the specified condition is met. A do-while loop is recommended if the number of iterations is not fixed, and the loop must be executed at least once.

The do-while loop is also known as an exit control loop. Unlike while and for loop, the do-while loop checks the condition at the end of the loop. That’s why the do-while loop is executed at least once.

The generalised form of the do-while loop is given below:

do{    
//body
//iteration statement   
}
while (condition); 

Every iteration of the do-while loop first executes the loop’s body and then evaluates the condition. If the condition holds, the loop will repeat. Otherwise, the loop terminates.

A simple program to demonstrate do while loop in Java is given below:

class DoWhile 
{
public static void main(String args[]) 
{
int n = 5;
do 
{
System.out.println("Coding Ninjas " + n);
n--;
}while(n > 0);
}
}

Output:

Coding Ninjas 5
Coding Ninjas 4
Coding Ninjas 3
Coding Ninjas 2
Coding Ninjas 1

Here’s how it works:

  • Inside do, it prints “Coding Ninjas” with the counter variable and then the value of n decreases by 1. 
  • After that, the value is compared to zero. If it’s greater than zero, the loop will continue, otherwise, it’ll terminate.

For loop in Java

The Java for loop is the most powerful and versatile of iterative statements.

The generalised form of for loop is given below:

for(initialisation; condition; iteration) 
{ 
// body 
}

When the loop starts, the initialisation part of the loop is executed. The initialisation is an expression that sets the loop control variable’s value, which acts as a counter that controls the loop.

The mechanism of for loop is as follows:

  • The initialisation expression is only executed once. Next, the condition is evaluated. 
  • The condition should be a boolean expression. It tests the loop control variable with a given value. 
  • If the condition holds, then the loop’s body is executed. 
  • If the condition doesn’t hold, the loop terminates. 
  • Then the iteration part of the loop is executed. Iteration expression increases or decreases the value of the loop control variable. 
  • The loop then evaluates the conditional expression, then executes the loop’s body.
  • Then the loop executes the iteration expression with every pass.

Program to demonstrate the for loop in Java:

public class ForTest 
{
public static void main(String args[]) 
	{
	    int n;
	    for(n=5; n>0; n--)
	         System.out.println("Coding Ninjas " + n);
	}

}

When we run this program, it will print “Coding Ninjas” along with the counter variable five times.

Output:
Coding Ninjas 5
Coding Ninjas 4
Coding Ninjas 3
Coding Ninjas 2
Coding Ninjas 1

Points to remember:

  • The variable inside the initialisation portion can be initialised in place as well. For example, for(int n=10; n>0; n–) Note: The scope of the variable is limited to the for loop.
  • We can include more than one statement in the initialization and iteration portions of the for loop. This can be done using the comma “,”. For example, for(a=1, b=4; a<b; a++, b–) Note: The initialisation portion sets the values of both a and b simultaneously.

Variations of For loop

The for loop supports several variations that increase its power and applicability. The reason for flexibility is that it has three parts:

  • The initialisation
  • The conditional test, and
  • The iteration

These parts are not used only for predefined purposes. We can use these three sections for any purpose. Let’s look at some examples.

  • Use of conditional expressions: The condition controlling the for loop can be any boolean expression. 

For example:

boolean flag = false; 
for(int i=1; !done; i++) 
{ 
flag = true; 
}

In the above example, the for loop does not depend on the value of i. And runs until the done variable is set to true. 

  • Absence of initialisation or iteration expression:  In Java for loop, the initialisation or the iteration expression or both may be absent, as shown in the given program.
public class ForVariation 
{
public static void main(String args[]) 
{
int i;
boolean flag = false;
i = 0;
for( ; !flag; ) 
{
System.out.println("i is " + i);
if(i == 5)
flag = true;
i++;
}
}
}

Here, the initialisation and iteration expressions are moved out of the for loop. Note: This is considered a poor style of initialisation in Java.

Nested For loop

A for loop inside the body of a for loop is known as a nested for loop. When we need to repeat an action on the data in the outer loop with every pass, nested loops are handy. 

For example, While reading a file line by line and counting how many times the word “the” is found. The outer loop will read the lines, while the inner loop runs through the words in each line, looking for “the.”

A java program for printing a pattern using nested loops is as follows: 

public class Nested 
{ 
public static void main(String args[]) 
{ 	
int i, j; 
int n = 5;
for(i=0; i<n; i++) 
{ 
for(j=i; j<n; j++) 
System.out.print(". "); 
System.out.println(); 
} 
} 
}

Output:

. . . . . 
. . . . 
. . . 
. . 
. 

In the above code, we have initialized a variable n=5 to enter the number of rows for the pattern. The range of the outer for loop will be 0 to 4.

  • The iteration of the inner for loop depends on the outer loop. The inner loop is used to print the number of columns.
  • In the first iteration, the value of i is 0, so j starts from 0 and until j is less than 5 a dot will get printed with space.
  • This gets repeated n number of times.
  • The last print statement prints a line after each row.

Foreach loop in Java

In JDK 5, a new variation of for loop was introduced known as for each loop. A for each loop in Java is used to iterate through a set of objects, such as an array, from beginning to end in a strictly sequential manner.

The general form of the for-each version is given below: 

for(type var : collection) 
statement-block

Here, type specifies the type of collection, and var is the name of an iteration variable that will receive elements from a collection one by one from start to end. 

In every iteration of the loop, the next element in the collection is fetched in var. The loop is repeated until the entire collection has been retrieved.

A simple program to demonstrate the Java for-each loop is given below:

public class For_Each    
{
    public static void main(String[] arg)
    {
            int[] marks = { 15, 13, 19, 16, 10 };
            // for each loop
            for (int num : marks)
            {
            	System.out.println(num); 
            }
    }
}

Output:

15
13
19
16
10

Let’s see the difference between for and for each via a comparison.

int collect[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++) 
sum += collect[i];
int collect[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
int sum = 0; 
for(int x: collect) 
sum += x;

Limitations of for each loop are as follows:

  • More overhead cost than simple iteration methods.
  • Used to iterate in the forward direction only.
  • They cannot modify the collection.

Note: Unlike some languages that implement a for-each loop using the keyword foreach, Java added the for-each capability by enhancing the for statement.

Do you want to boost your self-esteem by solving problems and earning points? Check out the Iterative Statement problems in CodeStudio and put in some serious practise time, champ.

Never Quit! It might look hard initially, but remember that practice makes perfect. The adrenaline rush you will get when the idea of a problem clicks in mind after struggling for many hours is worth the effort. So push yourself to be one of the best programmers.

Frequently Asked Questions

What are the three types of loops in Java?

The three main types of loops in Java are for, while and do-while.

What are loops in Java?

Loops in Java are used to repeatedly execute the same set of instructions before a termination condition is met.

What is a for loop used for Java?

For loop is used to repeat the execution statements many times without actually writing it in the program.

Do loops in Java need brackets?

If the body of the loop contains only one statement, then brackets are not used. But, for more than one statement inside a loop, curly braces are used to enclose them.

Why do we need loops in Java?

Loops in Java facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true.

What are the different types of loops in Java?

There are mainly three types of loops in Java, while, do-while and for loop. For each loop is an enhanced version of for loop in Java.

Key Takeaways

This blog unfolds the concept of various loops in Java. These looping statements have great importance in programming. Also, if you are wishing to learn more about looping statements in various other languages, Here’s a quick guide to follow:

Java is one of the most popular languages, it finds wide applications in Android development and server development, learning Java in-depth will definitely get you a lucrative placement.

To learn more about Java, take a look at various courses offered by Coding Ninjas. To know more about the best books of Java, check out our blog on 21 Best Java Programming Books for Beginners & Experts.

Happy Learning!

By Vaishnavi Pandey