Vikash Singh
@full_stack_geek
Different types of for loops in
Java
Vikash Singh
@full_stack_geek
1) Java For Loop
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution
of the code block.
Statement 2 defines the condition for executing the
code block.
Statement 3 is executed (every time) after the code
block has been executed.
for (int i = 0; i < 5; i++) {
[Link](i);
}
Vikash Singh
@full_stack_geek
2) For-Each Loop
There is also a "for-each" loop, which is used
exclusively to loop through elements in an array
for (type variableName : arrayName) {
// code block to be executed
}
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
[Link](i);
}
Vikash Singh
@full_stack_geek
3) forEach()
Java provides a new method forEach() to iterate the elements.
It is defined in Iterable and Stream interface. It is a default
method defined in the Iterable interface. Collection classes
which extends Iterable interface can use forEach loop to
iterate elements.
default void forEach(Consumer<super T>action)
List<String> gamesList = new ArrayList<String>();
[Link]("Football");
[Link]("Cricket");
[Link]("Chess");
[Link]("Hocky");
[Link](games -> [Link](games));