Loops in Java Explained

Loops in Java Explained

7 mins read2.5K Views Comment
Updated on Jan 27, 2023 15:26 IST

The below article covers the iteration statements or loops in Java. It goes through the working of loops with implementation and examples.

2022_06_loops.jpg

Contents

Introduction

Loops or iteration statements come under the umbrella of control structures in Java. The control statements, as the name suggest, control or direct the flow of execution in a program. 

Generally, there are 3 types of Control Structures in Java:

Let’s understand Iteration Statements or loops in Java.

What are Loops in Java?

Imagine a scenario wherein your requirement is to execute a statement repeatedly. Say you have to print all the even numbers between 1-100. The result of this execution requires you to check again and again if the number is divisible by two or not. Then print those numbers accordingly. Individual calculation and execution of each line will take a tedious amount of time. It invokes the requirement of iteration statements or loops in Java Programming.

Iteration statement saves a lot of time and effort for the programmer.

Also Read: Variables in Java

Iteration statements or Loops in Java help to perform a task repeatedly so that we don’t have to write the code explicitly again and again. That’s the reason they are popularly called loops since they work in a loop to complete a particular task.

Types of Loops in Java

There are generally 3 types of loops in Java:

For Loop

The for loop statement creates iteration over a collection of values. These values can be of different types. Moreover, it’s an entry control loop since one can’t enter the loop until the condition evaluates as true.

Syntax:

 
for (initialization; termination condition; increment/decrement)
{
//Set of statements to be executed repeatedly
}
Copy code

Working of For Loop

  • The initialization in a for loop is the starting point of a loop with an initial value assigned to a variable. It serves as an entry point in a loop. 
  • The termination condition acts as the exiting condition in a loop. The condition always evaluates to a boolean value. Hence, the loop runs till the time the condition is true. Moreover, the flow exits from the loop as soon as the condition turns false.
  • The increment/decrement operation applies to progressively execute the loop. Hence, it can proceed onto its next iteration.
  • The beginning and ending curly braces indicate the statements that will get executed as a part of for loop. FYI, the for loop without curly braces simply means that there is only one statement under the loop which happens to be the immediate next statement.
  • The three conditions (initialization, termination, and increment/decrement) in for loop are optional.
for

Example:

 
//Program to print even numbers between 1-10.
class ForLoopDemo {
public static void main(String[] args) {
for (int i=1; i<=10; i++)
{
if (i%2==0)
System.out.println(i);
}
System.out.println("Loop Ending");
}
}
Copy code

Explanation:

1st Iteration: i=1: The value of i=1 and it’s less than equals 10. Hence, we enter the loop executing the if statement. Since 1%2 is not equal to 0. 1 is not printed. Now, the value of i=1 increments by 1.

2nd Iteration: i=2: The value of i=2 and it’s less than equals 10. Hence, we enter the loop executing the if statement. Since 2%2 is equal to 0. 2 gets printed. Now, the value of i=2 increments by 1.

. . . .  

And the loop goes until it reaches i=11 and the loop terminates as 11>10. Hence, Loop end.

Output:

output1

Empty For Loop

Empty for loop is without a body. These statements execute only once rather than getting executed a number of times or infinitely. It is declared using a semicolon after for loop declaration.

 
for( int k = 10 ; k >=0 ; k-- ) ;
//the loop has no body with only semicolon at the end
Copy code

Infinite For Loop

There are times when you need to run the loop infinitely. In such conditions, we have two ways:

  1. No termination point declared: 
 
class Infinite_ForLoopDemo
{
public static void main(String args[])
{
int x;
for( x = 10 ; ; x-- )//No termination Declared
System.out.println(“Infinite loop”);
}
}
Copy code
  1. No declaration inside for loop:
 
class Infinite_ForLoopDemo
{
public static void main(String args[])
{
for( ; ; ) //No declaration
System.out.println(“Infinite loop”);
}
}
Copy code

Read: Difference between JDK, JVM and JRE.

For-Each Loop

For-each loop is used to iterate over a group of elements like an array. It is generally used to traverse each element of an array.

Syntax:

 
for (int t : array_name)//here, the variable t iterate over the array_name
{
//statements to iterate
}
Copy code

Example:

 
class ForEach_Loop_Demo
{
public static void main(String args[])
{
int array1[] = {1,2,3,4,6,7,8,9,10};
for( int i:array1)
{
System.out.println(i);
}
}
}
Copy code

Output:

output2

Also, Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained

While Loop

The while is another iteration statement to iterate over different types. It accepts a condition and evaluates it to a boolean value. If the value is true only then, the statements under the loop get executed. Else the control jumps out of the loop.

It’s also an entry control loop since one can’t enter the loop until the condition evaluates as true.

Working of While Loop

While loop works the same as for loop. Initialization → Termination Condition → Increment/Decrement.

while

Syntax:

 
//initialization
while (condition)
{
//Execute a set of statements
//increment
}
Copy code

Example:

 
class While_Loop_Demo
{
//print even numbers ranging from 1 to 10
public static void main(String args[])
{
int i = 1; //initialization
while (i<=10) //condition or termination
{
if (i%2==0)
{
System.out.println(i);
}
i++; //increment
}
}
}
Copy code

Explanation:

1st Iteration: i=1: The value of i=1 and it’s less than equals 10. Hence, we enter the loop executing the if statement. Since 1%2 is not equal to 0. 1 is not printed. Now, the value of i=1 increments by 1.

2nd Iteration: i=2: The value of i=2 and its less than equals 10. Hence, we enter the loop executing the if statement. Since 2%2 is equal to 0. 2 gets printed. Now, the value of i=2 increments by 1.

. . . .  

And the loop goes until it reaches i=11 and the loop terminates as 11>10. Hence, Loop end.

Output:

output3

Empty While Loop

Empty while loop condition is followed by a semicolon. These statements execute only once rather than getting executed a number of times or infinitely.

 
class Empty_While_Loop_Demo
{
public static void main(String args[])
{
int i = 1; //initialization
while (i<=10); //condition or termination
//the semicolon shows termination of while loop which infers that while loop has no definition
{
System.out.println(i);
i++; //increment
}
}
}
Copy code

Infinite While Loop

The while loop will iterate the statements until the condition is true.

 
while(true)
{
//statements to be executed infinite times
System.out.println(“This is an infinite loop”);
}
Copy code

Note: Jump statements can be used to get out of infinite loops.

Also Read: Java Operators Explained

Do-While Loop

Do-while first executes the statements under do then check the condition under while. Hence, the statements under do will at least be executed once even if the condition evaluates to false. This is the reason it’s called an exit control loop.

It is one of the major differences between while and do-while loops.

Syntax:

 
do
{
//statements to be iterated
}
while(conditions);
Copy code

Working of Do-While Loop

Initialization → Execution → Termination condition check.

do-while

Example:

 
class Do_While_Loop_Demo
{
//print even number
public static void main(String args[])
{
int i = 1; //initialization
do
{
System.out.println(i);
i++; //increment
} while (i%2==0);//condition or termination
}
}
Copy code

Explanation:

1st iteration: i=1: prints the value 1 and increment the value of i by 1. Then checks the conditions. Hence, even if i is not divisible by 2 still it got printed as an output.

2nd Iteration: i=2: The value of i=2. Since 2%2 is equal to 0. 2 gets printed. Now, the value of i=2 increments by 1.

Now the value of i=3 and it does not satisfy the condition 3%2 is not equal to 0. Hence, the loop terminates.

Output:

output4

Infinite Do-While Loop

The infinite do-while loop can be implemented in the following way.

 
do
{
//statements to be iterated infinitely
}
while(condition==true);
Copy code

For more, read: 8 Most Important Data Structures a Programmer Must Know

Conclusion

The article explains loops in Java with examples and different implementations. Hope you learned something new reading it. If you have any queries please share them in the link below. Happy learning!

To learn more, Go for Best Courses on Java Programming

_________________

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

FAQs

What are Control Statements in Java?

It controls the flow or direction of the execution of the program. Control here implies branching, decision-making, and iterating. These are in 3 categories: conditional, iterative, and jump statements.

What are Iteration Statements in Java?

Iteration statements or Loops in Java help to perform a task repeatedly so that we donu2019t have to write the code explicitly again and again. They work in a loop to complete a particular task.

Why do we use loops in Java?

Loops usage decreases the efforts and time to write code for repeated executable statements.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio