For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 10 AM to 7 PM
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
Ever needed to repeat a task 10, 100, or even 1,000 times in your code? That's where the for loop comes in, it's your personal automation tool for any repetitive job.
This tutorial is your complete guide to writing a For Loop Program in Java. We'll break down its simple three-part structure, show you how to loop through arrays and collections, and even explore the curious (and sometimes dangerous) case of the infinite for loop in Java.
By the end, you'll have the confidence to use this essential tool to write cleaner and more powerful code. Let's get looping!
Looking to advance your Java framework skills? Check out upGrad’s Online Software Engineering Courses. Start today to strengthen your foundation and accelerate your career growth by learning JavaScript, Node.js, APIs, React, and more!
Here are the details for the three parts of a 'For Loop' in Java:
1. Initialization Expression
This starts the loop. It initializes the loop variable. Usually, we use it to set a counter to a specific value. It executes only once.
2. Test Expression
This checks a condition. If it returns true, the loop continues. If it returns false, the loop ends. We usually check if the counter has reached a certain value.
3. Update Expression
This updates the loop variable. After each loop iteration, this expression runs. We often use it to increment or decrement the counter.
Accelerate your tech career by mastering future-ready skills in Cloud, DevOps, AI, and Full Stack Development. Gain hands-on experience, learn from industry leaders, and develop the expertise that top employers demand.
Loop Type | Initialization | Test Before Iteration | Runs at Least Once | Update Statement |
Yes | Yes | No | Yes | |
While Loop | No | Yes | No | No |
No | No | Yes | No |
For Loop initializes a counter, tests before iteration, and contains an update statement within the loop structure itself.
While Loop in Java checks the condition before entering the loop but does not have an inherent initialization or update statement.
Do-While Loop ensures the code block executes at least once, as it checks the condition after running the loop. But similar to While Loop, it lacks inherent initialization and update statements.
Also Read: JDK in Java: Comprehensive Guide to JDK, JRE, and JVM
The 'For Loop' structure in Java is as follows:
For loop in Java example:
Here's a simple example of a 'For Loop' that prints numbers from 1 to 5:
In this case, int i=1 is the initialization part, where we initialize our counter i to 1.
i<=5 is the test expression. Before each loop iteration, we check if this condition is true. If i is less than or equal to 5, we continue the loop. If not, we stop the loop.
i++ is the updated expression. After each iteration of the loop, we increase i by one.
Running this code, you'll see the numbers 1 through 5 printed on your console.
Also Read: Control Statements in Java: Types, Flowcharts, and Code Examples
Here's what each part does:
Also Read: 50 Java Projects With Source Code in 2025: From Beginner to Advanced
Java offers many types of 'For Loops' for diverse scenarios. They are:
1. Simple For Loop
The basic form of 'For Loop' we discussed earlier is the Simple For Loop. It consists of initialization, testing, and update expressions.
Example:
2. Enhanced For Loop (For Each Loop)
The Enhanced For Loop, also known as the "for-each" loop, is designed for iteration over arrays or collections, making the code more readable.
Example:
3. Labeled For Loop
A Labeled For Loop allows us to name our loops. This can be beneficial when we have nested loops and want to break or continue a specific outer loop.
Example:
4. Infinite For Loop
An Infinite For Loop continues indefinitely. This happens if the test condition never becomes false. It's usually a coding error, but can sometimes be useful.
Example:
These variations offer flexibility to handle different scenarios in programming with Java.
Also Read: File Handling in Java: How to Work with Java Files?
Remember, 'For Loops' are excellent for cases where you know how many times the loop should run.
Explanation:
This is a typical flowchart for a 'For Loop' in Java. It illustrates the cyclic and iterative nature of the loop, helping understand the flow of the loop process.
The For-Each Loop, also known as the Enhanced For Loop, offers a simpler way to iterate over arrays or collections. It's ideal for scenarios where you don't need to manipulate the elements' indexes.
Here's its general structure:
Type represents the data type of the elements. var is the variable that takes the value of each element during the iteration. array is the array or collection you're traversing.
Example
Consider the following array of integers:
Here, number takes on the value of each element in the numbers array. The loop prints out these values one by one. So, the output would be 1, 2, 3, 4, and 5, each on a new line.
Output
Note
While the For-Each Loop is simple and easy to use, it doesn't provide control over the index. You can't know the index of the current element within the loop, nor can you alter the iteration step (like skipping every other element). If you need such control, use a traditional For Loop.
The For-Each Loop also works great with collections. Here's an example with an ArrayList:
Output
In this example, name takes the value of each element in the names ArrayList. The loop prints out these names one by one. So, the output would be Alice, Bob, Charlie, each on a new line.
Also Read: Java Language History: Why Java Is So Popular and Widely Used Today
An Infinite For Loop is a loop that runs indefinitely. This usually occurs when the condition in the loop never becomes false. It's often due to a programming error, but sometimes, it's intentional.
Here's the structure of an Infinite For Loop:
Example
Here's an example of an infinite loop that would print "Hello, World!" endlessly:
Note
Running an infinite loop like the one above will print "Hello, World!" continuously until you manually stop the program.
In practical scenarios, infinite loops are not usually desirable as they can cause the program to become unresponsive or consume too much CPU time. Yet, they can be useful in cases where a program needs to run indefinitely until it's manually stopped, such as a server waiting for client requests.
Also Read: Top 10 Java Frameworks Powering Modern Application Development
Please be careful when running infinite loops, as they can make your program run indefinitely, consuming system resources. Always ensure there's a valid way to stop the loop.
A Nested For Loop in Java means there is a For Loop inside another For Loop. It's very useful when dealing with multi-dimensional data structures like arrays.
Here's the structure:
Example
An example of a nested for loop that prints a 5x5 matrix:
Output
The output would be:
This forms a 5x5 matrix, where each row is the numbers 1 through 5.
Nested For Loops are very useful in Java for manipulating multi-dimensional data structures or performing repeated operations.
In short, you now know how to write a For Loop Program in Java, from its basic structure to the cautionary infinite for loop in java. This is a core skill for handling any repetitive task, especially with arrays and collections, allowing you to write much cleaner and more efficient code.
Leaving out a part of the 'For Loop' syntax can have different effects. For instance, if you omit the initialization part, you must ensure the loop variable is initialized elsewhere in the code. If the condition is absent, the loop becomes an infinite loop.
Absolutely! You can use other data types such as byte, short, long, or even char for the loop variable. However, the choice should make sense according to your looping requirements. For example, using a double or float is generally unusual, unless you need to increment by fractions.
A 'For Loop' with an empty body will still execute the initialization, condition check, and increment/decrement operations. However, since the body is empty, no substantial work gets done inside the loop. In most scenarios, having an empty loop body would not be useful.
Java provides many alternatives for iterative operations, such as 'While Loop' and 'Do-While Loop'. These control structures can be used interchangeably, depending on the specific use-case. Moreover, Java provides a stream API and methods like forEach for collections, offering a functional programming approach to iterations.
-9cd0a42cab014b9e8d6d4c4ba3f27ab1.webp&w=3840&q=75)
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free

Author|907 articles published