The for loop in Java is a control flow statement that is used to repeatedly execute a block of code for a specific number of iterations. It is particularly useful when you know beforehand how many times the loop needs to run.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Explanation
1. Initialization: This is executed only once at the beginning of the loop. It is typically used to declare and initialize the loop control variable.
2. Condition: This is evaluated before each iteration. If the condition evaluates to true, the loop continues; otherwise, the loop stops.
3. Update: This is executed after each iteration and is usually used to update the loop control variable.
Example: print value from 1 to 5 through for loop
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
}
}
Output:
Count: 1Count: 2
Count: 3
Count: 4
Count: 5
Working Process:
1. Initialization: int i = 1; sets the loop control variable i to 1.
2. Condition: i <= 5; checks if i is less than or equal to 5.
3. Body Execution: The code inside the loop (System.out.println) is executed.
4. Update: i++ increments i by 1 after each iteration.
For Each loop
A for-each Style loop is designed to cycle through a collection of objects, such as an array, in a strictly sequential fashion, from start to finish. Unlike some languages, such as C#, that implement a for-each loop by using the keyword foreach, Java adds the for-each capability by enhancing the for statement. The advantage of this approach is that no new keyword is required, and no preexisting code is broken.
The for-each style of for is also referred to as the enhanced for loop.
The general form of the for-each version of the for is shown here:
Syntax:
for(type itr-var : collection) statement-block
Example:
// Use a for-each style for loop.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
The output from the program is shown here:Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55
Reverse Loop
Loops can count down instead of up.
public class ReverseForLoop {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
System.out.println("Count: " + i);
}
}
}
Output:
Count: 5Count: 4
Count: 3
Count: 2
Count: 1
Nested for Loop
You can use one for loop inside another to handle multidimensional scenarios, like printing patterns.
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Output:
i: 1, j: 1i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
...
i: 3, j: 3
Enhanced for Loop (for-each Loop)
Used to iterate over arrays or collections.
Example with Arrays:
public class ForEachLoop {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
}
}
Output:
1020
30
40
50
Skipping a Loop
Skip the current iteration and move to the next.
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // Skip when i is 3
System.out.println("Count: " + i);
}
}
}
Output:
Count: 1Count: 2
Count: 4
Count: 5
Using break
Exit the loop prematurely.
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // Stop when i is 3
System.out.println("Count: " + i);
}
}
}
Output:
Count: 1Count: 2
Infinite Loop
A for loop can run indefinitely if no stopping condition is provided.
public class InfiniteLoop {
public static void main(String[] args) {
for (;;) {
System.out.println("This is an infinite loop.");
}
}
}
Java for Loop – Interview Questions
Q 1: What is a for loop in Java?
Ans: A loop used when the number of iterations is known.
Q 2: What are the parts of for loop?
Ans: Initialization, condition, and increment/decrement.
Q 3: Can for loop run without initialization?
Ans: Yes, initialization is optional.
Q 4: Can a for loop be nested?
Ans: Yes, loops can be nested.
Q 5: When should for loop be used?
Ans: When loop count is fixed.
Java For Loop – Objective Questions (MCQs)
Q1. Which of the following is the correct syntax of a for loop in Java?
Q2. How many times will the following loop execute?
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Q3. What will be the output of the following code?
for (int i = 0; i < 3; i++) {
System.out.print(i + ' ');
}
Q4. Which of the following statements is true about the for-each loop in Java?
Q5. What is the output of the following code?
int sum = 0;
for (int i = 1; i <= 3; i++) {
sum += i;
}
System.out.println(sum);