Table of Contents
1. Introduction
There are several looping statements available in Java, one of which is the for loop. The for loop in Java is used to execute a set of statements repeatedly until a specified condition evaluates to false.
It provides a compact way to initialize a loop variable, check a condition, and update the loop variable. It’s especially useful when we know in advance how many times we want to repeat the execution.
2. The Structure of a For Loop
1 2 3 4 5 |
for (initialization; condition; step) { //block of statements } |
- Initialization: This is executed once at the beginning of the loop. It often involves declaring and initializing a loop control variable.
- Condition: Before each iteration, the loop checks this condition. If the condition evaluates to
true
, the loop continues; if it evaluates tofalse
, the loop ends. - Step: This statement is executed after each iteration. It typically involves incrementing or decrementing the loop control variable.
The Initialization, condition and step used in for statements are optional.
3. Basic For Loop Example
To illustrate, let’s write a Java program that uses a for loop to print numbers from 1 to 5:
1 2 3 4 5 6 7 8 9 |
public class ForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); } } } |
In this example, int i = 1
is the initialization where we start counting from 1. The condition i <= 5
ensures that the loop continues as long as i
is less than or equal to 5. The step i++
increments i
by 1 after each iteration.
1 2 3 4 5 6 7 |
1 2 3 4 5 |
If you are still confused by the above concept, let’s understand it with the help of a flow diagram:
Let’s try to print only even numbers now:
1 2 3 4 5 6 7 8 9 10 11 |
public class ForLoopMain { public static void main(String[] args) { for (int i = 1; i < 11; i++) { if(i%2==0) System.out.print(" "+i); } } } |
Output:
1 2 3 |
2 4 6 8 10 |
4. Advanced For Loop Concepts
Java for loops are versatile and can be used in various forms to suit different scenarios:
4.1 Labeled For Loops
Java provides a feature called labeled loops, which is particularly useful in nested loop scenarios where you might need to break out of an outer loop from within an inner loop.
A label is an identifier followed by a colon (:
) placed before a loop statement, which can then be referenced in break or continue statements to control the flow more precisely.
Here’s an example of using a labeled for loop:
1 2 3 4 5 6 7 8 9 10 11 |
outerLoop: // This is the label for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { if (i * j > 6) { System.out.println("Breaking at i=" + i + ", j=" + j); break outerLoop; // Breaks out of the outer loop } } } |
In this example, the outerLoop
label is associated with the outer for loop. When the condition i * j > 6
is met within the inner loop, the break outerLoop
statement terminates the outer loop, not just the inner one. This feature adds a level of control that allows you to exit multiple loops at once, making it especially handy in complex looping scenarios where simply breaking out of the current loop isn’t sufficient.
4.2 Using Two Variables in For Loop
For loops can use multiple variables, useful for simultaneous iterations or complex conditions.
Let’s say you want to check if a string is a palindrome or not. You can use two variables in the for loop as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; public class StringUsingHalfLoop { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a string : "); String str = scanner.nextLine(); boolean isPalin = isPalindrome(str); if (isPalin) System.out.println("String is Palindrome"); else System.out.println("String is not Palindrome"); } static boolean isPalindrome(String str) { for (int i = 0, j = str.length() - 1; i < str.length() / 2; i++, j--) { if (str.charAt(i) != str.charAt(j)) { return false; } } return true; } } |
1 2 3 4 5 6 |
Enter a string : madam String is Palindrome Enter a string : adam String is not Palindrome |
In the provided program, two variables, i
and j
, are used in the for loop to check if the input string is a palindrome. Variable i
starts from the beginning of the string (0
index), and j
starts from the end (str.length() - 1
), moving towards each other to compare characters at mirrored positions until the middle of the string is reached or a mismatch is found.
4.3 Infinite For Loop
An infinite for loop runs endlessly. It’s useful in scenarios where a task needs to repeat indefinitely until externally stopped, such as in server processes or listening for events.
1 2 3 4 5 |
for (;;) { // Infinite execution block } |
You need to be careful with the condition you provide in the for loop; otherwise, you may end up creating an infinite loop.
For example, let’s say you want to print numbers from 10 to 1 and you use the code below:
1 2 3 4 5 6 7 8 9 10 |
public class ForLoopMain { public static void main(String[] args) { for (int i = 10; i >0; i--) { System.out.print(" "+i); } } } |
1 2 3 |
10 9 8 7 6 5 4 3 2 1 |
In the code above, if you use i++ instead of i–, the loop will enter an infinite loop.
1 2 3 4 5 6 7 8 9 10 |
public class ForLoopMain { public static void main(String[] args) { for (int i = 10; i >0; i++) { System.out.print(" "+i); } } } |
4.4 Enhanced For Loop
Introduced in Java 5, also known as the “for-each” loop, it is ideal for iterating over arrays or collections. It eliminates the need for a counter or iterator variable, making the code cleaner and less prone to errors. This loop is elegant for reading each element in a collection without explicit indexing.
The syntax of the enhance for loop is as follows:
1 2 3 4 5 |
for (Type var : arrayOrCollection) { // Statements using var } |
- Type: The data type of the elements in the array or collection.
- var: The variable that represents the current element in the loop.
- arrayOrCollection: The array or collection being iterated over.
Let’s say we have an array of integers and we want to print each element:
1 2 3 4 5 6 |
int[] numbers = {1, 2, 3, 4, 5}; for (int number : numbers) { System.out.println(number); } |
This for-each loop reads as “for each int number
in numbers
, print number
“.
1 2 3 4 5 6 7 |
1 2 3 4 5 |
This loop iterates over each element in the numbers
array, assigning each element in turn to the variable number
and then executing the loop’s body.
Given a List<String> listOfStrings
object – We can iterate it as follows:
1 2 3 4 5 |
for (String element : listOfStrings) { System.out.println(element); } |
5. Exercise
Let’s apply our knowledge of for loops by writing a program.
Given an array of integers like {32, 45, 53, 65, 43, 23}
, your task is to search for a specific element within this array. If the element exists, your program should output ‘PRESENT’; if it doesn’t, it should output ‘NOT PRESENT’.
I would recommend that you try it yourself first and then look at the code below:
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class ForStatementExample { public static void main(String[] args) { ForStatementExample bse=new ForStatementExample(); int arr[] ={32,45,53,65,43,23}; System.out.println(bse.findElementInArr(arr, 53)); } public String findElementInArr(int arr[],int elementTobeFound) { for (int i = 0; i < arr.length; i++) { if(arr[i]==elementTobeFound) { System.out.println(elementTobeFound+" is present in the array "); return "PRESENT"; } } return "NOT PRESENT"; } } |
Output:
1 2 3 4 |
53 is present in the array PRESENT |
6. Conclusion
The for loop in Java is a powerful control flow statement that enables concise and readable iteration over a block of code. Whether you’re counting numbers, iterating over arrays, or traversing collections, understanding and using for loops effectively can make your Java programs more efficient and expressive.