The for
loop in Java is a control flow statement that iterates a part of the programs multiple times. It’s ideal for when you know in advance how many times you want to execute a block of code. Here, we’ll explore the for
loop through various examples, explaining their use and function.
Basic for
Loop
A basic for
loop includes initialization, condition, and increment/decrement in a single line, making it concise and easy to understand.
Example:
1 2 3 4 5 6 7 8 9 10 |
// Print numbers from 1 to 5 for (int i = 1; i <= 5; i++) { System.out.println(i); } // Output: // 1 // 2 // 3 // 4 // 5 |
Looping Through an Array
You can use a for
loop to iterate through each element of an array.
Example:
1 2 3 4 5 6 7 8 9 |
// Print all elements in an array String[] fruits = {"Apple", "Banana", "Cherry"}; for (int i = 0; i < fruits.length; i++) { System.out.println(fruits[i]); } // Output: // Apple // Banana // Cherry |
Enhanced for
Loop (For-Each)
Java provides the enhanced for
loop, also known as the for-each loop, which simplifies iterating through arrays or collections.
Example:
1 2 3 4 5 6 7 8 9 |
// Print each element in an array using for-each loop String[] colors = {"Red", "Green", "Blue"}; for (String color : colors) { System.out.println(color); } // Output: // Red // Green // Blue |
Nested for
Loops
You can use a for
loop inside another for
loop to iterate over two dimensions, which is particularly useful for matrices.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
// Print a 3x3 matrix for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { System.out.print(i * j + " "); } System.out.println(); // Move to the next line } // Output: // 1 2 3 // 2 4 6 // 3 6 9 |
Infinite for
Loop
An infinite loop runs forever unless the program is terminated. It can be created by leaving the condition empty.
Example:
1 2 3 4 5 6 |
// Infinite loop for (;;) { System.out.println("This loop will run forever."); // Remember to break out of the loop or terminate the program to stop execution. break; // Uncommenting this line will stop the infinite loop. } |
for
Loop with Multiple Variables
You can initialize and update multiple variables in a single for
loop.
Example:
1 2 3 4 5 6 7 8 9 10 |
// Using multiple variables in for loop for (int i = 1, j = 1; i <= 5; i++, j++) { System.out.println("i=" + i + ", j=" + j); } // Output: // i=1, j=1 // i=2, j=2 // i=3, j=3 // i=4, j=4 // i=5, j=5 |
These examples illustrate the versatility of the for
loop in Java, showing how it can be used for simple counting, iterating over arrays and collections, handling nested loops, and even managing multiple variables within a single loop. Understanding how to effectively use for
loops enhances your ability to write concise and efficient Java code.
Using break
in a For Loop
The break
statement terminates the loop immediately when it’s executed. It’s useful when you need to stop the loop execution under certain conditions before it naturally concludes.
Example: Find the first number divisible by 7 in a range.
1 2 3 4 5 6 7 |
for (int i = 1; i <= 100; i++) { if (i % 7 == 0) { System.out.println("First number divisible by 7 is: " + i); break; // Exits the loop } } // Output: First number divisible by 7 is: 7 |
In this example, the loop searches for the first number divisible by 7 between 1 and 100. Once found, it prints the number and exits the loop using break
.
Using continue
in a For Loop
The continue
statement skips the current iteration of the loop and proceeds to the next iteration. It’s used to skip over certain conditions within the loop.
Example: Print all numbers from 1 to 10 except those divisible by 3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
for (int i = 1; i <= 10; i++) { if (i % 3 == 0) { continue; // Skips the rest of the loop body for this iteration } System.out.println(i); } // Output: // 1 // 2 // 4 // 5 // 7 // 8 // 10 |
Here, the loop iterates from 1 to 10. The continue
statement is used to skip printing numbers that are divisible by 3, resulting in only non-multiples of 3 being printed.
Combining break
and continue
While break
and continue
serve different purposes, they can be used together within a loop to control its execution more granely.
Example: Exit the loop after printing the first 5 numbers, skipping any number that is divisible by 4.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
for (int i = 1, count = 0; i <= 100; i++) { if (i % 4 == 0) { continue; // Skips numbers divisible by 4 } System.out.println(i); count++; if (count == 5) { break; // Exits the loop after printing 5 numbers } } // Output: // 1 // 2 // 3 // 5 // 6 |
In this combined example, the loop is controlled to print the first 5 numbers that are not divisible by 4 by using both continue
to skip unwanted numbers and break
to exit after meeting the desired count.
These examples illustrate the versatility of break
and continue
in controlling the execution flow of for
loops in Java, enabling more complex and conditional iterations tailored to specific programming needs.
For-Each Loop
The “for-each” loop, also known as the enhanced for
loop, was introduced in Java 5. It offers a simpler way to iterate through elements in arrays and collections without using an index variable. The for-each loop is particularly useful when you need to access each element in a collection or array sequentially without modifying the array’s contents.
Syntax of the For-Each Loop
The basic syntax of the for-each loop is as follows:
1 2 3 |
for (declaration : expression) { // Statements } |
- declaration: The newly declared block variable, of a type compatible with the elements of the array or collection being accessed.
- expression: This must evaluate to an array or a Java Iterable object.
Examples of For-Each Loop
Iterating Over an Array
1 2 3 4 5 6 7 8 |
String[] colors = {"Red", "Green", "Blue"}; for (String color : colors) { System.out.println(color); } // Output: // Red // Green // Blue |
In this example, the for-each loop iterates over the colors
array. The variable color
is automatically set to each element in the array, one at a time, and printed out.
Iterating Over a Collection
Collections in Java, such as ArrayList
, can also be iterated using the for-each loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import java.util.ArrayList; import java.util.List; public class ForEachExample { public static void main(String[] args) { List<String> fruitList = new ArrayList<>(); fruitList.add("Apple"); fruitList.add("Banana"); fruitList.add("Cherry"); for (String fruit : fruitList) { System.out.println(fruit); } // Output: // Apple // Banana // Cherry } } |
This example shows how to iterate over a List
of String
objects. Each element in the list is accessed in order and printed.
Using For-Each with Multidimensional Arrays
While the for-each loop is straightforward for single-dimensional arrays, it requires a bit more work for multidimensional arrays since you need to use a nested for-each loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int[] row : matrix) { for (int element : row) { System.out.print(element + " "); } System.out.println(); } // Output: // 1 2 3 // 4 5 6 // 7 8 9 |
In this multidimensional array example, the outer for-each loop iterates over each row
of the matrix, and the inner loop iterates over each element
in the row.
Benefits of Using For-Each Loop
- Clarity and Conciseness: The for-each loop is more readable, especially when the index is not needed within the loop body.
- Reduces Errors: By eliminating the need for an index variable, it minimizes the risk of programming errors, such as off-by-one errors.
- Enhanced for Collections: It abstracts the iterator, making the code cleaner and more straightforward when working with collections.
The for-each loop is a powerful feature for iterating over collections and arrays in Java, making code more readable and reducing the chance of errors. It is particularly useful in scenarios where you need to perform operations on each element of a collection or array but do not need to modify the underlying structure.