Java For Loop Syntax and Example
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
In this article, we are going to focus on Java for loop.
A loop is anything that is done repetitively.
Take an example of your daily routine, you wake up, you brush, have a bath, and then set off for work. You repeat this every day.
Your brain performs these functions automatically without you realizing it. This concept of performing a set of tasks repetitively is looping.
Whenever you know the exact number of times a particular set of programs is to be performed, you use for loop in java.
Java For loop
In Java, “for loops” are loops that run for a predetermined number of times. The for loop in Java follows a particular pattern. It contains the following parts
- The initialization
- The condition
- The increment/decrement
- The statements.
Syntax
for(control_variable initialize value; condition for control_variable;Increment or decrement control variable) { //Loop Body }
Control Flow of Java For Loop
The loops in java follow a particular pattern for execution.
1. Initialization – This process primarily focuses on initializing or providing initial values to a variable. This is the first step in the looping process.
Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!
2. Checking condition – As the name suggests, after the variable is initialized, it checks whether the value satisfies the condition of the loop.
Once the condition evaluates to true, the content inside the loop starts to execute. However, if the condition evaluates to false, the control shifts outside the loop.
3. Loop Body – The next step in execution is the body of the loop. There is a common misconception about the fact that the increment or decrement happens after the condition is checked.
But this is wrong as the control shifts to the body of the loop as soon as the condition of the loop evaluates to true.
4. After all the lines inside the body of the loop are executed perfectly, the control shifts to the increment/decrement section.
Here the value of the counter gets modified and the loop continues.
Flowchart of the control flow of for loop in Java
Java program to understand the concept of for loops in Java
package com.dataflair.javaforloop; public class JavaForLoop { public static void main(String[] args) { System.out.println("We will be learning about for loops"); int i; for(i=0;i<5;i++) { System.out.println("Currently in Loop. value of i = "+i); } System.out.println("Currently outside Loop. value of i = "+i); } }
Output:
Currently in Loop. value of i = 0
Currently in Loop. value of i = 1
Currently in Loop. value of i = 2
Currently in Loop. value of i = 3
Currently in Loop. value of i = 4
Currently outside Loop. value of i = 5
Java program to iterate an array using for loop
package com.dataflair.javaforloop; import java.io.*; public class ArrayTraverse{ public static void main(String []args) { int arrp[] = {1,2,3,4,5,6}; for(int i=0;i<arrp.length;i++) { System.out.println("The "+(i+1)+" element is "+arrp[i]); } } }
Output:
The 2 element is 2
The 3 element is 3
The 4 element is 4
The 5 element is 5
The 6 element is 6
Enhanced For Loops(For-each loops) in Java
In java, there is a certain type of a “for loop” that enables you to traverse through any collection. This is a “for each” loop.
However, there is a catch. You cannot edit any value as the object used for traversing in an enhanced loop is immutable.
In normal for loops, you could alter the value inside the loop, but in enhanced for loops, you can only view the data. You cannot change it.
According to Java docs, the syntax of Enhanced for loops is as follows.
for( T object : Collection) { //Code to be executed in the loop }
Java program to illustrate the concept of enhanced for loops
package com.dataflair.javaforloop; import java.util.*; public class EnhancedForLoop { public static void main (String[]args) { ArrayList<Integer>values=new ArrayList<>(); for(int variable=10;variable<=50;variable+=10) { values.add(variable);//Adding the elements in the list. } System.out.println("Now we will use the for each loop to print the elements in the ArrayList"); for(Integer i:values) { System.out.print(i+" "); } } }
Output:
10 20 30 40 50
Infinite For Loop
An infinite “For loop” is a loop that runs indefinitely. You can make a for loop run infinitely in many ways.
Let us see an example of Java Infinite For Loop:
for(i=13;i>=10;i++) { //These statements run infinitely }
We can observe that the value of “i” starts with 13 and keeps on increasing. This loop never stops.
Infinite for loops is something that may happen due to a flawed logic.
However, sometimes infinite loops are also purposefully added in code to serve some kind of a continuously executing function.
Java Nested For loop
The term nested for loop simply means a for loop inside another for loop. It is pretty simple to understand.
For each iteration of the outer for loop, the inner for loop executes a fixed number of times.
This nested for loop allows us to print patterns in Java.
A simple example of a pattern is given below.
package com.dataflair.javaforloop; import java.io.*; public class NestedPattern{ public static void main(String []args) { int arrp[] = {1,2,3,4,5,6}; for(int i=0;i<arrp.length;i++) { for(int j=0;j<i;j++) { System.out.print("*"); } System.out.println(""); } } }
Output:
**
***
****
*****
Java Labelled For Loop
There are often times when we need to use nested loops in Java and thus need to break the outer loop instead of the inner loop. This can be made possible by Java Labels for For Loops.
We can label each and every for loop in Java. However, they are particularly useful when we need to continue or break a specific loop.
Confused? Do not worry. Let us take a look at an example.
Java program to illustrate the use of Labelled For loops
package com.dataflair.javaforloop; public class LabelledForLoops { public static void main(String[] args) { int i,j; System.out.println("Let us see an example where we use nested loops without labels. "); for(i=1;i<=5;i++) { for(j=1;j<=5;j++) { System.out.println(i+" "+j); if(i==j) break; } System.out.print("\n"); } System.out.println("Now let us see the difference when we use labels. "); aa: for(i=1;i<=5;i++) { bb: for(j=1;j<=5;j++) { System.out.println(i+" "+j); if(i==j) break aa; } System.out.print("\n"); } } }
Output:
1 12 1
2 23 1
3 2
3 34 1
4 2
4 3
4 45 1
5 2
5 3
5 4
5 5Now let us see the difference when we use labels.
1 1
If you observe, it is evident that we can only break the outer loop with the help of labels. This is one of the primary uses of labelled for loops in Java.
Common Errors to Avoid while using For Loops in Java
While for loops appear straightforward, there are potential pitfalls to be aware of. Here are some common mistakes to avoid:
1. Incorrect initialization or termination condition: Ensure your loop’s initialization value and termination condition are set correctly to prevent infinite loops or unintended behavior.
2. Modifying the control variable within the loop body: If you plan to modify the control variable within the loop, exercise caution to prevent unexpected loop termination or infinite execution.
3. Infinite loops: Accidental infinite loops can occur due to incorrect conditions. Double-check your loop logic to ensure it terminates as intended.
Summary
Summing up, looping is an integral part of programming and for loops are extremely useful as it allows us to repeatedly execute statements when we know how many times we want to repeat them.
We learned about for loops, its syntax, and enhanced for-loops along with examples.
If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google