Java for loop and enhanced for loop is a type of control flow statement which provides a compact way to iterate over a range of values. for loop repeatedly loops through the code until a particular condition is satisfied.
Over the period, Java has added different types of for loop.
- for loop
- Enhanced for loop or foreach
for loop
for loop is a combination of 3 expressions, which needs to be understood in order to use for loop efficiently.
- The initialization expression initializes the loop; it’s executed once, as the loop begins.
- termination expression is used to stop the loop. It gets evaluated with every iteration and when the termination expression evaluates to
false
, the loop terminates. - The increment/decrement expression is invoked after each iteration through the loop.
Syntax of for loop
for(Initialization; Termination; Increment/ Decrement){ //Code to execute in loop }
for loop example
public class for_loop {
public static void main(String[] args) {
for (int i = 0; i < 4; i++) {
System.out.println("Value of i: " + i);
}
int j;//declare variable outside for loop if needed beyond loop
for (j = 4; j < 8; j++) {
System.out.println("Value of j: " + j);
}
int k = 8;
for (; k < 12; k++) {
System.out.println("Value of k: " + k);
}
}
}
Output of the above program
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of j: 4
Value of j: 5
Value of j: 6
Value of j: 7
Value of k: 8
Value of k: 9
Value of k: 10
Value of k: 11
Here code declares an int variable i within the initialization expression. The scope of variable i extends from its declaration to the end of the for statement block, so it can be used in the termination and increment expressions as well.
If the variable that controls a for
statement is not needed outside of the loop, it’s best to declare the variable in the initialization expression. As you can see in the first for loop
using i int variable. Declaring them within the initialization expression limits their life span and reduces errors.
The names i
, j
, and k
are often used to control for
loops.
Please note that the three expressions of the for loop are optional. Hence both below code are valid, though it will create an infinite loop
for (; ; k++) {
System.out.println("Infinite loop");
}
for (; ; ) {
System.out.println("Infinite loop");
}
Enhanced for loop
The enhanced for
loop is another form of for loop. It was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection and Arrays. It can make your loops more compact and easy to read.
Enhanced for loop syntax
for (datatype obj : array / collection ) {}
Enhanced for loop example
import java.util.Arrays;
import java.util.List;
public class for_loop {
public static void main(String[] args) {
//enhanced for loop
String[] array = {"Hello ", "Hi ", "How ", "are ", "you?"};
List<String> list = Arrays.asList(array);
for (String str : array) {
System.out.print(str);
}
System.out.println("\n");
for (String str : list) {
System.out.print(str);
}
}
}
The output of the above code is
Hello Hi How are you?
Hello Hi How are you?
enhanced for loop iterates through each object in the given collection or array, stores each object in a variable (obj), and executes the body of the loop.
It is recommended to use enhanced for loop wherever possible.
It is not possible to find the present index in an enhanced for loop. In scenarios where you want index number either you use the old for loop or you can try the below alternatives to get the index number.
import java.util.Arrays;
import java.util.List;
public class for_loop {
public static void main(String[] args) {
//enhanced for loop
String[] array = {"Hello ", "Hi ", "How ", "are ", "you?"};
List<String> list = Arrays.asList(array);
int index = 0;
for (String str : array) {
System.out.print(str);
System.out.println("Current Index :" + index++);
}
System.out.println("\n");
for (String str : list) {
System.out.print(str);
System.out.println("Current Index: " + list.indexOf(str));
}
}
}
The output of the code
Hello Current Index :0
Hi Current Index :1
How Current Index :2
are Current Index :3
you?Current Index :4
Hello Current Index: 0
Hi Current Index: 1
How Current Index: 2
are Current Index: 3
you?Current Index: 4