Java for Loop with Examples
In this quick article, we will discuss for loop with examples. The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the “for loop” because of the way in which it repeatedly loops until a particular condition is satisfied.
Table of contents
- Java for Loop Syntax
- How for Loop Works
- Simple for Loop Example
- Using the Comma
- The For-Each Version of the for Loop
- for-each Loop with Break
- for-each Loop is Essentially Read-Only
- for-each - Iterating Over Multidimensional Arrays
- Search an Array Using for-each Style Example
- Nested for Loops
Java for Loop Syntax
for (initialization; termination;
increment) {
statement(s)
}
The initialization expression initializes the loop; it’s executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
How for Loop Works (Flow of Execution of the for Loop)
-
First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.
-
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
-
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.
-
Fourth step: After the third step, the control jumps to the second step and condition is re-evaluated.
Simple for Loop Example
package net.javaguides.corejava.controlstatements.loops;
public class ForLoopExample {
public static void main(String args[]) {
// here, n is declared inside of the for loop
for (int n = 10; n > 0; n--)
System.out.println("tick " + n);
}
}
Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Note that we have declared a loop control variable inside the a for loop. When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does.
When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i , is declared inside the for since it is not needed elsewhere.
package net.javaguides.corejava.controlstatements.loops;
public class ForLoopFindPrime {
public static void main(String args[]) {
int num;
boolean isPrime;
num = 14;
if (num < 2)
isPrime = false;
else
isPrime = true;
for (int i = 2; i <= num / i; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}
if (isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}
Output:
Not Prime
Using the Comma
There will be times when we will want to include more than one statement in the initialization and iteration portions of the for loop. For example, consider the loop in the following program:
package net.javaguides.corejava.controlstatements.loops;
public class ForLoopComma {
public static void main(String args[]) {
int a, b;
for (a = 1, b = 4; a < b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}
Output:
a = 1
b = 4
a = 2
b = 3
In this example, the initialization portion sets the values of both a and b. The two commas separated statements in the iteration portion are executed each time the loop repeats.
The For-Each Version of the for Loop
Beginning with JDK 5, the second form of for was defined that implements a “for-each” style loop. Enhanced for loop is useful when you want to iterate Array/Collections, it is easy to write and understand.
Syntex
for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will receive the elements from a collection, one at a time, from beginning to end.
Here is an entire program that demonstrates the for-each version:
package net.javaguides.corejava.controlstatements.loops;
public class ForEachExample {
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);
}
}
Output:
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
for-each Loop with Break
It is possible to terminate the loop early by using a break statement. For example, this program sums only the first five elements of nums:
package net.javaguides.corejava.controlstatements.loops;
public class ForEachWithBreak {
public static void main(String args[]) {
int sum = 0;
int nums[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
// use for to display and sum the values
for (int x: nums) {
System.out.println("Value is: " + x);
sum += x;
if (x == 5)
break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Summation of first 5 elements: 15
for-each Loop is Essentially Read-Only
There is one important point to understand about the for-each style loop. Its iteration variable is “read-only” as it relates to the underlying array. An assignment to the iteration variable has no effect on the underlying array. In other words, we can’t change the contents of the array by assigning the iteration variable a new value.
For example, consider this program:
package net.javaguides.corejava.controlstatements.loops;
public class ForEachNoChange {
public static void main(String args[]) {
int nums[] = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
for (int x: nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for (int x: nums)
System.out.print(x + " ");
System.out.println();
}
}
Note that the first for loop increases the value of the iteration variable by a factor of 10. However, this assignment has no effect on the underlying array nums, as the second for loop illustrates.
for-each - Iterating Over Multidimensional Arrays
The enhanced version of the for also works on multidimensional arrays. The following program uses the for-each style for a two-dimensional array:
package net.javaguides.corejava.controlstatements.loops;
public class ForEachMultidimensionalArrays {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for (int i = 0; i < 3; i++)
for (int j = 0; j < 5; j++)
nums[i][j] = (i + 1) * (j + 1);
// use for-each for to display and sum the values
for (int x[]: nums) {
for (int y: x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90
Search an Array Using for-each Style Example
The following program uses a for each loop to search an unsorted array for a value. It stops if the value is found.
package net.javaguides.corejava.controlstatements.loops;
public class ForEachSearchArray {
public static void main(String args[]) {
int nums[] = {
6,
8,
3,
7,
5,
6,
1,
4
};
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for (int x: nums) {
if (x == val) {
found = true;
break;
}
}
if (found)
System.out.println("Value found!");
}
}
Output:
Value found!
The for-each style for is an excellent choice in this application because searching an unsorted array involves examining each element in a sequence.
Nested for Loops
Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:
package net.javaguides.corejava.controlstatements.loops;
public class NestedForLoops {
public static void main(String args[]) {
int i, j;
for (i = 0; i < 10; i++) {
for (j = i; j < 10; j++)
System.out.print(".");
System.out.println();
}
}
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.