Loops in Java Explained
The article below covers iteration statements or loops in Java. It explains how loops work with implementation and examples.
Contents
Best-suited Java courses for you
Learn Java with these high-rated online courses
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:
- Conditional Statements or Decisional Statements (if, if-else, switch)
- Iteration Statements (for, while, do-while, for-each)
- Jump Statements (break, continue, return)
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
}
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. It always evaluates to a boolean value. Hence, the loop runs until the condition is true. Moreover, the flow exits from the loop as soon as the condition turns false.
- The increment/decrement operation applies to execute the loop progressively. Hence, it can proceed to its next iteration.
- The beginning and ending curly braces indicate the statements that will be executed as part of the for loop. FYI, a 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.
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");
}
}
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.
. . . .
The loop goes until it reaches i=11, and then it terminates as 11>10. Hence, the Loop ends.
Output:
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
Infinite For Loop
There are times when you need to run the loop infinitely. In such conditions, we have two ways:
- 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”);
}
}
- No declaration inside for loop:
class Infinite_ForLoopDemo
{
public static void main(String args[])
{
for( ; ; ) //No declaration
System.out.println(“Infinite loop”);
}
}
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
}
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);
}
}
}
Output:
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.
Syntax:
//initialization
while (condition)
{
//Execute a set of statements
//increment
}
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
}
}
}
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:
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
}
}
}
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”);
}
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);
Working of Do-While Loop
Initialization → Execution → Termination condition check.
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
}
}
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:
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);
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.
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