The most common and one of the most important topics of Java is “for loop”.In Java, a “for” loop is a control flow statement used for repeatedly executing a block of code based on a specified condition. It’s like having a machine that does the same task repeatedly until a specific condition is met or a certain number of times have passed. It provides a concise and structured way to perform repetitive tasks in your code. The for loop is commonly used when you know the required number of iterations.
The syntax of a “for” loop in Java is as follows:
for (initialization; condition; increment/decrement) {
// Code block to be executed repeatedly
}
Let’s break down the different parts of the “for” loop:
- Initialization: This part is executed only once at the beginning of the loop. It is used to set up the loop control variable(s) and initialize them to a specific value. Typically, you declare and initialize a loop control variable here.
- Condition: The condition is evaluated before each iteration of the loop. If the condition evaluates to true, the loop’s code block is executed; otherwise, the loop terminates, and the program moves on to the next statement after the loop.
- Update: The update part is executed after each iteration of the loop. It is used to modify the loop control variable(s) so that the loop can progress toward its termination. For example, you can increment or decrement the loop control variable(s) in this section.
- Code block: This is the block of code that will be executed repeatedly as long as the condition evaluates to true. The code block can contain any Java statements, and it will be executed in each iteration of the loop.
Let’s see a simple example of a “for” loop in Java that prints the numbers from 1 to 5
public class For_Loop { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); } } }
Output:
1
2
3
4
5
Explanation:
- Initialization: int i = 1 sets the loop control variable i to 1.
- Condition: i <= 5 checks if the value of i is less than or equal to 5. If this condition is true, the loop continues; otherwise, it terminates.
- Update: i++ increments the value of i by 1 after each iteration.
- The loop runs for i = 1, i = 2, i = 3, i = 4, and i = 5, printing the values in each iteration until the condition i <= 5 becomes false, and the loop terminates.
You can use “for” loops to iterate over arrays, and collections, or perform other tasks that require repetitive execution based on a specific condition. The loop control variable(s) and the condition can be modified based on the specific requirements of your program.
Another Example:
public class For_Loop { public static void main(String[] args) { for(int i = 2; i<=10; i=i+2){ System.out.println(i); } } }
Output:
2
4
6
8
10
Explanation:
- for(int i = 2; i <= 10; i = i + 2): This is a for loop that initializes a variable i to 2. It will execute the loop as long as i is less than or equal to 10. After each iteration, the value of i will be incremented by 2 (due to i = i + 2).
- Inside the loop’s body: System.out.println(i);: This line prints the value of i to the console in each iteration.
Let’s see what happens in each iteration:
Initial value of i: 2
2 is printed to the console.
Value of i: 4
4 is printed to the console.
Value of i: 6
6 is printed on the console.
Value of i: 8
8 is printed on the console.
Value of i: 10
10 is printed on the console.
Why do we use for loop?
- Iterating over a range of values: When you need to perform a specific task a fixed number of times, a for loop is a convenient choice. For example, if you want to print numbers from 1 to 10 or process data for a set number of iterations, a for loop allows you to define the range of values easily and execute the code repeatedly.
- Processing elements in arrays or collections: Arrays and collections often contain multiple elements that you want to process one by one. A for loop provides a simple way to iterate through all the elements and perform the same operations on each element.
- Reducing repetitive code: Instead of writing the same code multiple times, you can place the repetitive code inside a for loop. This reduces redundancy in your code and improves its maintainability. It’s a way to follow the DRY principle (Don’t Repeat Yourself).
- Controlled looping with a counter: You can use a loop control variable (usually an integer) to control the number of iterations in the loop. This gives you the ability to define a termination condition based on the value of the counter variable, allowing you to precisely control the flow of your program.
- Simplifying complex tasks: In more complex scenarios, a for loop can simplify the logic of solving problems by dividing them into smaller, manageable steps. It helps break down the problem into smaller parts and handle each part within the loop.
- Enhancing code readability: Using a for loop makes your code more expressive and readable. The structure of the loop clearly indicates that a repetitive task is being performed, making the intent of the code more evident to other developers
break and continue keyword in for loop
break:
The break statement is used to terminate the loop prematurely, breaking out of the loop entirely. When a break statement is encountered inside a loop, the loop is immediately exited, and the program continues executing from the statement immediately after the loop.
Here’s an example of using break in a for loop to stop the loop when a specific condition is met:
public class For_Loop { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Terminate the loop when i is 5 } System.out.println(i); } } }
Output:
1
2
3
4
In this example, when i become 5, the break statement is executed, and the loop is terminated immediately. As a result, only the numbers 1 to 4 are printed.
continue:
The continue statement is used to skip the rest of the current iteration and jump to the next iteration of the loop. When a continue statement is encountered inside a loop, the loop’s remaining code for the current iteration is skipped, and the loop immediately proceeds with the next iteration (if any).
Here’s an example of using continue in a for loop to skip printing even numbers:
public class For_Loop { public static void main(String[] args) { for (int i = 1; i <= 10; i++) { if (i % 2 == 0) { continue; // Skip even numbers } System.out.println(i); } } }
Output:
1
3
5
7
9
In this example, when i is even, the continue statement is executed, and the System.out.println(i) statement is skipped. As a result, only the odd numbers are printed.
It’s important to use continue and break judiciously to avoid creating complex and hard-to-maintain code. Used appropriately, these statements can help control the loop flow and improve the efficiency of your code.