1. What is a for loop in Java and when do we use it ?
A for loop in Java is used when we know in advance how many times a block of code needs to be executed. It has three parts: initialization, condition, and update.
Example: Printing numbers from 1 to 5 using for loop
Output
1
2
3
4
5
Use a for loop when the number of iterations is known before execution (e.g., printing first 10 numbers, traversing an array).
2. What is an enhanced for loop in Java and why is it used ?
The enhanced for loop (also called the for-each loop) is used to iterate over arrays or collections without using an index. It makes code simpler and easier to read.
Example: Iterating over an array using enhanced for loop
Output
Apple
Banana
Mango
Use an enhanced for loop when you want to process elements directly, without caring about indexes.
3. How do you write an infinite for loop in Java?
A for loop can run forever if we omit the condition. This is often used in servers or event listeners.
Example: Infinite loop
for(;;) {
System.out.println("Running...");
break; // add break to avoid actual infinity
}
Output:
Running...
Use infinite loops carefully. Always include break or return to stop execution when needed.
4. What is a labeled for loop and when should you use it?
A labeled for loop allows breaking or continuing outer loops in nested loop structures.
Example: Breaking out of nested loops
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
if(i == 2 && j == 2) break outer;
System.out.println(i + " " + j);
}
}
Output:
1 1
1 2
1 3
2 1
Use labeled loops only when deeply nested loops require controlled exits.
5. How can you optimize a for loop for performance?
In large loops, avoid recalculating values like arr.length multiple times. Store them in a variable for efficiency.
Example: Optimized array traversal
int[] arr = {1, 2, 3, 4, 5};
for(int i = 0, n = arr.length; i < n; i++) {
System.out.println(arr[i]);
}
Output:
1
2
3
4
5
Optimization matters when handling large data sets or performance-critical code.
6. How does a nested for loop work in Java?
A nested for loop means having one loop inside another. It is often used in matrices or patterns.
Example: Printing a 3×3 matrix {
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output:
1 2 3
1 2 3
1 2 3
Nested loops are useful for 2D arrays, grids, or patterns, but they can increase time complexity.
7. Can a for loop have no body in Java?
Yes. If all logic fits in initialization, condition, or update, the loop body can be empty.
Example: Printing numbers 1 to 5 without a body
for(int i = 1; i <= 5; System.out.println(i++));
Output:
1
2
3
4
5
Empty-body loops are rare but can make code concise in special cases.