0% found this document useful (0 votes)
66 views4 pages

Types of For Loops in Java

The document discusses three types of for loops in Java: 1) the basic for loop that uses three statements to initialize a counter, check a condition, and increment the counter, 2) the for-each loop that iterates through elements in an array, and 3) the forEach() method that iterates through elements in a Collection and is defined in the Iterable and Stream interfaces.

Uploaded by

Aahil Aaryan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views4 pages

Types of For Loops in Java

The document discusses three types of for loops in Java: 1) the basic for loop that uses three statements to initialize a counter, check a condition, and increment the counter, 2) the for-each loop that iterates through elements in an array, and 3) the forEach() method that iterates through elements in a Collection and is defined in the Iterable and Stream interfaces.

Uploaded by

Aahil Aaryan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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));

You might also like