For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
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.
A for loop is a fundamental control flow statement that allows you to execute a block of code a specific number of times. When writing a For Loop Program in Java, you use this structure for tasks where you know the exact number of iterations in advance, like counting from 1 to 10 or processing every element in an array. Its concise structure is key to avoiding an accidental infinite for loop in java, where the loop's condition to stop is never met.
The classic For Loop Program in Java has a syntax that is neatly organized into three parts within parentheses, separated by semicolons:
Leaving out a part of a For Loop Program in Java syntax can have different effects, and you must be careful not to create an infinite for loop in java. For instance, if you omit the initialization, you must ensure the loop variable is declared and initialized before the loop begins. If the condition is absent, the loop assumes the condition is always true and becomes an infinite loop. If you omit the increment/decrement, the loop variable will never change, likely resulting in another infinite for loop in java.
A For Loop Program in Java is typically used when the number of iterations is known beforehand. Its syntax neatly packages the initialization, condition, and increment logic in one line. A while loop, on the other hand, is used when the number of iterations is unknown and the loop continues as long as a condition is true. While you can replicate a for loop with a while loop, it's easier to forget the increment step in a while loop, making it more prone to causing an accidental infinite for loop in java.
The enhanced for loop (or for-each loop) provides a simpler, more readable syntax for iterating through all the elements of an array or a collection. When writing a For Loop Program in Java to process every item in a list, the for-each loop is often preferred as it handles the indexing and condition checks for you. This simplification also makes it impossible to create an infinite for loop in java by mistake, as the loop automatically terminates after the last element.
Java
// Example of an enhanced for loop
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
In a For Loop Program in Java, these two statements give you more control over the loop's execution:
Using these correctly is vital, as improper logic with continue could potentially prevent the loop's condition from ever being met, risking an infinite for loop in java.
A nested For Loop Program in Java is a loop inside another loop. The outer loop controls the number of repetitions for the inner loop. For each single iteration of the outer loop, the inner loop completes its entire sequence of iterations. This is commonly used for working with 2D arrays (like grids or matrices) or for printing patterns. It's important to manage the conditions of both loops carefully to prevent a situation where the inner or outer loop becomes an infinite for loop in java.
Yes, you can declare and manage multiple variables within the initialization and increment/decrement sections of a For Loop Program in Java, separating them with commas. This can be useful for more complex iterations, such as iterating from both ends of an array towards the middle. However, you can only have one boolean expression in the condition part. Mismanaging the logic for multiple variables can make the code hard to read and could lead to an unexpected infinite for loop in java.
Java
// Example with multiple variables
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i: " + i + ", j: " + j);
}
Absolutely! When creating a For Loop Program in Java, you are not restricted to int. You can use other data types such as byte, short, long, or even char for the loop variable. The choice should make sense for your requirements. Using a double or float is less common but possible, though you must be cautious with the condition, as floating-point precision issues could accidentally create an infinite for loop in java.
The scope of a variable refers to where it can be accessed. When you declare a variable inside the initialization part of a For Loop Program in Java (e.g., for (int i = 0; ...)), its scope is limited to the loop itself. This means you can only use the variable i inside the loop's body and its control statements. Once the loop finishes, the variable is destroyed and cannot be accessed from outside. This helps prevent naming conflicts and is a key concept to grasp to avoid conditions that could cause an infinite for loop in java.
A For Loop Program in Java with an empty body (a semicolon immediately after the parentheses) will still execute its initialization, condition check, and increment/decrement operations for each iteration. However, since the body is empty, no other work gets done. This can be used intentionally for tasks like finding a specific index or creating a delay, but it's often a source of bugs for beginners who place a semicolon by mistake. This could also easily become an infinite for loop in java if the condition is never met.
An infinite for loop in java occurs when the loop's termination condition never becomes false. The most common mistakes when writing a For Loop Program in Java that lead to this are:
A classic For Loop Program in Java is perfect for iterating through an array because arrays have a fixed size, which is known in advance. You typically initialize a counter variable i to 0 and loop while i is less than the array's length (array.length). Inside the loop, you use i as the index to access each element (array[i]). It's crucial that the condition is < array.length and not <=, as the latter would cause an ArrayIndexOutOfBoundsException and is a different kind of error than an infinite for loop in java.
You can use a classic For Loop Program in Java to iterate over an ArrayList by using its size() method in the condition (i < list.size()). However, the enhanced for-each loop is a much cleaner and safer way to do this. The for-each loop abstracts away the index and condition, simply giving you each element in the collection one by one. This also has the added benefit of making it impossible to accidentally create an infinite for loop in java.
Yes, a nested For Loop Program in Java is ideal for printing 2D patterns like triangles of stars. The outer loop typically controls the number of rows, and the inner loop controls the number of columns (or stars) in each row. The logic in the inner loop's condition often depends on the outer loop's variable. It is important to ensure both loops have proper termination conditions to avoid an infinite for loop in java.
Java
// Prints a right-angled triangle of stars
int rows = 5;
for (int i = 1; i <= rows; i++) { // Outer loop for rows
for (int j = 1; j <= i; j++) { // Inner loop for columns
System.out.print("* ");
}
System.out.println(); // Move to the next line after each row
}
To search for an element in an array, you can write a For Loop Program in Java that iterates through each element from the beginning. Inside the loop, an if statement checks if the current element matches the target element. If a match is found, you can use the break statement to exit the loop immediately, making the search more efficient. If the loop completes without finding the element, you know it's not in the array. This is a far better approach than risking an infinite for loop in java with a more complex structure.
A labeled For Loop Program in Java allows you to give a name (a "label") to a loop. This is primarily used with nested loops. A normal break or continue statement only affects the innermost loop it's in. By using a label (e.g., break outerLoop;), you can break out of or continue a specific outer loop from within an inner loop. This is an advanced feature and should be used sparingly as it can make code harder to read, but it's a powerful tool for controlling complex loops and avoiding logic that might lead to an infinite for loop in java.
In most modern Java applications, the performance difference between a classic For Loop Program in Java (with an index) and an enhanced for-each loop is negligible. The JVM is highly optimized for both. For ArrayLists, the performance is virtually identical. For LinkedLists, a classic for loop with list.get(i) can be very slow, and a for-each loop is much faster. However, unless you are working with millions of elements, choosing based on readability is usually the best practice to avoid errors like an infinite for loop in java.
Yes, Java provides several alternatives to a traditional For Loop Program in Java. The most common are the while loop and do-while loop. For collections, Java 8 introduced the Stream API with methods like forEach(), which provides a more modern, functional programming approach to iteration. These alternatives can be more readable for certain tasks and can also help avoid common mistakes like creating an infinite for loop in java.
Mastering the For Loop Program in Java is absolutely essential because iteration is a core concept in virtually all programming. It's used for data processing, algorithms, manipulating collections, and much more. A deep understanding of its different forms, control statements (break/continue), and potential pitfalls—especially how to avoid an infinite for loop in java—demonstrates a strong foundation in programming logic. This skill is a fundamental requirement for any developer and is a key topic covered in depth in upGrad's comprehensive Java development courses to prepare you for a successful career.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free
Author|900 articles published