In real-life software programming, there are many instances when we have to repeat a specific task again and again. There are two ways by which we can do such tasks. First, we can code the same thing again and again. This method is highly inefficient and violates the DRY (Don't Repeat Yourself) principle. The other option is to use a technique in Java which is known as loops. Loops are the iteration statements that are used to perform a certain task repeated a number of times without having to code again and again. It is highly efficient.
Java provides three types of iteration statements:
for statements
while statements
do-while statements
These iteration statements are commonly known as loops. We shall follow the same convention throughout this article.
Situations Where Loops Are Used
Whenever we want to access each element in an array, we can simply use a loop to iterate over the array and access each element. Trying to access each element by indexing would take hours if the array size is significantly large. Using loops, this can be done in seconds.
Suppose we want to execute a certain piece of code until a condition is true and we are not aware exactly when the condition is going to happen. In such cases, the while loop in the Java programming language can be used.
The for statement is used in the case of sequential traversal. Whenever we are aware of when to start the iteration and when to end it, we go for the for loop. The syntax of the for loop is very simple.
Syntax:
for(initialisation; condition; increment or decrement){
set of statements that we want to execute
}
You can also try this code with Online Java Compiler
We first initialise the iterating variable with a starting value. It is important to initialise the iterating variable; otherwise, the loop is unable to understand from where to begin.
Condition Checking
In each iteration, the value of the iterating variable is checked to ensure that it satisfies the condition of the loop. If the iterating value satisfies the condition, the control enters the body of the loop and executes the set of code statements. If the condition is not satisfied, the control comes out of the loop, and the loop is immediately terminated.
Body Of The Loop
The body of the for loop contains the set of code statements that the user wants to execute. The control enters the body of the for loop only if the condition is satisfied. We can also have a loop inside the body of a for loop. Such loops are popularly known as nested loops.
Incrementing Or Decrementing
After the control returns from the body of the loop, the value of the iterating variable is incremented or decremented. If the value is not incremented or decremented, then the condition would be true for every iteration, and then the loop would continue to execute until the program halts. This is known as the infinite loop.
Loop Termination
When the value of the iterating variable increments or decrements such that now it does not satisfy the condition of the loop, the control straight away comes out of the body of the loop, and the loop is then terminated.
Examples
Example 1: Print the first 10 natural numbers.
class ForLoopExample1 {
public static void main(String[] args) {
/*
step 1: declare iter_variable.
step 2: assign the initial value to 1.
step 3: set condition that iter_variable should not exceed 10
step 4: in the body of the loop print the ith natural number
step 4: increment the iter_variable value by 1 after every iteration.
*/
for(int iter_variable=1; iter_variable<=10; iter_variable++){
System.out.println(iter_variable);
}
}
}
You can also try this code with Online Java Compiler
class ForLoopExample2 {
public static void main(String[] args) {
/*
step 1: create a demoArray. We can take input from users too.
step 2: assign the initial value of i(iterating variable)to 1.
step 3: set the condition that the value of i should be less than the length of the array since we are considering 0 based index.
step 4: increment value of i by 1.
*/
int demoArray[]= {7,8,4,3,90,1,6,7,8,3,45,67};
for(int i=0;i<demoArray.length; i++){
System.out.println("Element number "+(i+1)+" is: "+demoArray[i]);
}
}
}
You can also try this code with Online Java Compiler
Element number 1 is: 7
Element number 2 is: 8
Element number 3 is: 4
Element number 4 is: 3
Element number 5 is: 90
Element number 6 is: 1
Element number 7 is: 6
Element number 8 is: 7
Element number 9 is: 8
Element number 10 is: 3
Element number 11 is: 45
Element number 12 is: 67
You can also try this code with Online Java Compiler
The for-each loop is an enhanced version of the for loop. The for-each loop is used for reading the values in sequential manner. We cannot modify the data using the for-each loop. We do not have to specify the index of the element.
Syntax:
for (T element:Collection obj/array)
{
code statements
}
You can also try this code with Online Java Compiler
Example 1: use for-each loop to iterate over an arraylist.
import java.util.*;
class For_eachExample1 {
public static void main(String[] args) {
// add some elements into an arraylist
ArrayList<Integer> list= new ArrayList<>();
for(int i=10;i>=0;i--){
list.add(i);
}
// for-each loop to access the elements of the list
for(Integer item : list){
System.out.println(item);
}
}
}
You can also try this code with Online Java Compiler
The while loop is a very common type of loop found in Java. We use a while loop mainly in cases where we do not have the exact idea when our iteration has to be stopped. Based on the condition provided, the while loop executes the statements inside the loop until the condition is true. Once the condition is false, the loop breaks, and the control comes out of the loop.
The while loop first checks the condition. If the condition, which is a boolean expression, evaluates to true, the control enters the body of the while loop, and the code within the body is executed. In case the expression evaluates to false, the control does not enter the body of the loop, and straightaway the loop is terminated. Because of this, the while loop is also known as the entry-control loop.
The flow chart of the while loop can be represented as:
Explanation
The while loop first checks the condition provided as the boolean expression. The control enters the body of the loop only if the condition is true; otherwise, the loop gets terminated. We can pass multiple conditions to the while loop. Based on the logical operation, the expression evaluates to true or false. It is not necessary that we have an iterating variable. However, we must then ensure that we use the break statement to terminate the loop after some time; otherwise, the while loop will continue executing till the program halts.
Example 1: print the first 10 natural numbers using a while loop.
class whileLoopExample1 {
public static void main(String[] args) {
int i=1; // initialise i=1
// iterate until i is less than or equal to 10
while(i<=10){
System.out.println(i);
i++; // increment i by 1
}
}
}
You can also try this code with Online Java Compiler
while(true) is an infinite loop, since the expression will always evaluate to true. However, once we find that the user has entered zero, we use the break statement. The break statement will bring the control out of the loop body. The control will not check any other line in the loop and will immediately come out of the loop.
Do-While Loop
The only difference between the do-while loop and the normal while loop is that the while loop checks the condition first and only if the condition evaluates to true then the control enters the body of the loop, whereas the do-while loop executes at least once and then checks the condition. Now it behaves similar to the while loop.
The do-while loop will execute for at least once. After that, the condition in the while() expression is checked. If the condition evaluates to true, the control goes back to the do block and executes the code inside the do block. If the condition evaluates to false, the control comes out of the loop, and the loop terminates.
Because the do-while loop does not check the condition first before executing the statement like the while loop, it is known as the exit control loop.
Examples
Example 1: Print the first 10 natural numbers using the do while loop.
class doWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
You can also try this code with Online Java Compiler
while loop is entry control loop whereas the do-while loop is exit control loop.
The do-while loop is executed at least once, whereas it may be possible that the control never enters the while loop body; hence the while loop may not be executed even once.
Variables involved in the condition have to be declared outside the loop, whereas we can declare the variable in the do block of the do-while loop.
Cautions
The loop statements obviously make our life easy. However, there are certain precautions that one should take while using loops in Java.
It is necessary to have a terminating condition; otherwise, the loop will continue to run until the memory limit exceeds. We must be aware of the break statement, which comes very handy when using the while loop.
Care must be taken while using loops with arrays. Trying to access the array elements beyond the range may throw an ArrayIndexOutOfBounds Exception.
The iteration statements are used to perform a certain task repeated a number of times without having to code again and again. It is highly efficient.
What are the various iteration statements available in Java?
The various iteration statements in Java are for statements, while statements, and do-while statements.
What is the difference between for and while loop?
The for loop is used for sequential iteration, whereas the while loop is mostly used when certain conditions are involved.
Which loop should one use when we are not aware of the terminating point?
We can use the while loop or the do-while loop.
What are the 3 types of iteration constructs?
The three types of iteration constructs are:
For loop: Executes a set of statements a fixed number of times.
While loop: Repeats a set of statements while a given condition is true.
Do-while loop: Repeats a set of statements at least once and then continues to repeat as long as a given condition is true.
Conclusion
Loops are the iteration statements that are used to perform a certain task repeated a number of times without having to code again and again.
The for statement is used in the case of sequential traversal. Whenever we are aware of when to start the iteration and when to end it, we go for the for loop.
We use a while loop mainly in cases where we do not have the exact idea when our iteration has to be stopped.
The do-while loop will execute for at least once.
while loop is entry control loop whereas the do-while loop is exit control loop.