For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Dive into the world of Java. Today's focus: the pivotal 'For Loop'. It's a cornerstone in coding, fundamental for iteration in Java.
In this tutorial, we will delve into the 'For Loop' structure, its applications, and nuances. You'll grasp why it's a key tool in a Java programmer's arsenal and gain practical knowledge to tackle real-world coding tasks with confidence.
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.
Loop Type | Initialization | Test Before Iteration | Runs at Least Once | Update Statement |
For Loop | Yes | Yes | No | Yes |
While Loop | No | Yes | No | No |
Do-While Loop | 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.
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.
Here's what each part does:
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.
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.
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.
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.
The 'For Loop' in Java is a versatile control structure, integral to iterative operations in your code. Whether it's the traditional 'For Loop', the 'Enhanced For-Each Loop', the 'Labeled For Loop', or even the 'Infinite For Loop', each variant presents unique utilities in different programming contexts. Coupled with the power of nested loops, these tools provide a robust approach to handling repetitive tasks efficiently. Mastery of 'For Loops' empowers you to deal effectively with arrays, collections, and multi-dimensional data structures, enhancing your Java programming proficiency.
1. What happens if I leave out a part of the 'For Loop' syntax in Java?
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.
2. Can I use data types other than int for the loop variable in a 'For 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.
3. How does 'For Loop' behave with an empty body?
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.
4. Are there alternatives to 'For Loops' in Java for iterative operations?
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.