for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
    String item = i.next();
    System.out.println(item);
}

Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.

As was noted by Denis Bueno, this code works for any object that implements the Iterable interface.

If the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. See the Java Language Specification.

for (int i = 0; i < someArray.length; i++) {
    String item = someArray[i];
    System.out.println(item);
}
Answer from nsayer on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
Java Examples Java Videos Java ... ... There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):...
Top answer
1 of 16
1310
for (Iterator<String> i = someIterable.iterator(); i.hasNext();) {
    String item = i.next();
    System.out.println(item);
}

Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for ( : ) idiom, since the actual iterator is merely inferred.

As was noted by Denis Bueno, this code works for any object that implements the Iterable interface.

If the right-hand side of the for (:) idiom is an array rather than an Iterable object, the internal code uses an int index counter and checks against array.length instead. See the Java Language Specification.

for (int i = 0; i < someArray.length; i++) {
    String item = someArray[i];
    System.out.println(item);
}
2 of 16
559

The construct for each is also valid for arrays. e.g.

String[] fruits = new String[] { "Orange", "Apple", "Pear", "Strawberry" };

for (String fruit : fruits) {
    // fruit is an element of the `fruits` array.
}

which is essentially equivalent of

for (int i = 0; i < fruits.length; i++) {
    String fruit = fruits[i];
    // fruit is an element of the `fruits` array.
}

So, overall summary:
[nsayer] The following is the longer form of what is happening:

for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);
}

Note that if you need to use i.remove(); in your loop, or access the actual iterator in some way, you cannot use the for( : ) idiom, since the actual Iterator is merely inferred.

[Denis Bueno]

It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.

Discussions

What is difference between for and foreach, and which is better?
foreach is used for iterating over anything that implements IEnumerable - Lists, arrays, collections, etc. It performs the action once for each element and gives you a reference to the current item. for is a general purpose loop that uses an initialiser, iterator and condition for control. It doesn't need a list object. for (initializer; condition; iterator) Which one is better to use depends on your use case. If you want to perform an action for every element in an IEnumerable, use foreach. For example, I want to give each of my employees a 10% raise: foreach (var emplyee in myCompany.Employees) { employee.Salary += employee.Salary / 10; } Use for when you want to do something a set number of times, or need complex control over the flow, such as making numbers count backwards, do something for ever odd number, etc. for (int i = 0; i < 100; i++) { // Count from 0 to 99 } for (int j = 100; j > 0; j--) { // Count from 100 to 1 } for (int k = 0; k < 100; k += 5) { // Count from 0 to 100 in steps of 5 } More on reddit.com
🌐 r/csharp
14
3
September 13, 2019
How does foreach Loop work in arraylist since the 'i' in for each loop is primitive
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
5
2
October 29, 2021
forEach loop not found in java?
String.split returns an array and not a collection Only collections have the .forEach method. You can wrap the array with Arrays.asList to get a list where you can call .forEach on. //Edit or can put the arrays value directly into a Stream. Streams have the forEach method as well. Arrays.stream(..) More on reddit.com
🌐 r/learnjava
6
7
October 16, 2020
Difference between for and for each?
The 'enhanced-for' is just 'syntax-sugar' for a for-loop (using a counter for arrays and an iterator for Iterables) Given `int[] numbers = {10, 20 ,30}; This... for (int value : numbers) { System.out.println(value); } is the same as... { int[] array = numbers; for (int len = array.length, i = 0; i < len; i++) { int value = array[i]; System.out.println(value); } } And given List strings = List.of("A", "B", "C") This... for (String value : strings) { System.out.println(value); } is the same as... for (Iterator i = strings.iterator(); i.hasNext(); ) { String value = i.next(); System.out.println(value); } Note that, in... for (int value : numbers) { System.out.println(value); } value is the value contained in the array, not an index used to access a value in the array. Your loop, using the enhanced-for, would need to keep a separate index variable. int[] ans = new int[nums.length * 2]; int i = 0; for (int value : nums) { ans[i] = value; ans[i + nums.length] = value; i++; } Or... If you want to be absolutely sure not to be hired in an interview... int[] ans = new int[nums.length * 2]; for (int value : nums) ans[ans[ans.length - 1]] = ans[nums.length + ans[ans.length - 1]++] = value; Edit: Fixed a code-typo More on reddit.com
🌐 r/learnjava
12
2
March 22, 2022
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › language › foreach.html
The For-Each Loop
5 days ago - Here is how the example looks with the for-each construct: void cancelAll(Collection<TimerTask> c) { for (TimerTask t : c) t.cancel(); } When you see the colon (:) read it as "in." The loop above reads as "for each TimerTask t in c." As you can see, the for-each construct combines beautifully with generics.
🌐
Runestone Academy
runestone.academy › runestone › static › JavaReview › ArrayBasics › aForEach.html
8.2. Looping with the For-Each Loop — AP CSA Java Review - Obsolete
A for-each loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last ...
🌐
Programiz
programiz.com › java-programming › enhanced-for-loop
Java for-each Loop (With Examples)
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
🌐
Baeldung
baeldung.com › home › java › core java › the for-each loop in java
The for-each Loop in Java | Baeldung
January 26, 2024 - The for-each loop was introduced in Java 5. We also call it an enhanced for loop. It’s an alternate traversing technique specifically introduced to traverse arrays or collections. Noticeably, it also uses the for a keyword.
🌐
IONOS
ionos.com › digital guide › websites › web development › java for-each loop
How to use for-each loops in Java - IONOS
November 3, 2023 - The basic syntax of a for-each loop in Java looks like this: for (type item : array | collection) { // code block }Java · array/collection: Name of the array or col­lec­tion · item: Each element of the array or col­lec­tion is assigned to this variable
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › enhanced-for-loops-in-java-how-to-use-foreach-loops-on-arrays
Enhanced For Loops in Java – How to Use ForEach Loops on Arrays
February 17, 2023 - You can use enhanced loops in Java to achieve the same results as a for loop. An enhanced loop is also known as a for-each loop in Java. Enhanced loops simplify the way you create for loops.
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
2 weeks ago - Explanation: In the above example, we use the for-each loop to iterate the list of integer to find the largest or maximum value in the list. Here, we use the Integer.MIN_VALUE which is the minimum value of integer and compare it the element of list and check if the element is greater than the max then update the max value.
🌐
W3Schools
w3schools.com › java › java_arrays_loop.asp
Java Loop Through an Array
This means: for each String in the cars array (here called car), print its value. Compared to a regular for loop, the for-each loop is easier to write and read because it does not need a counter (like i < cars.length).
🌐
Zero To Mastery
zerotomastery.io › blog › enhanced-for-loop-java
How To Use Enhanced For Loops In Java (aka 'foreach') | Zero To Mastery
January 26, 2024 - Always improving, Java 5 introduced the enhanced for loop as a part of its syntax enrichment. The enhanced for loop, otherwise known as a foreach loop, offers a simplified way to iterate over collections and arrays.
🌐
Javatpoint
javatpoint.com › for-each-loop
Java For-each Loop | Enhanced For Loop - javatpoint
January 2, 2023 - Java For-each loop | Java Enhanced For Loop: The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
🌐
Scaler
scaler.com › home › topics › java › for-each loop in java
For-each Loop in Java - Scaler Topics
January 31, 2026 - The for-each loop was introduced in Java 5 which is used specifically for traversing a collection in Java. In for-each loop traversal technique, you can directly initialize a variable with the same type as the base type of the array.
🌐
Tutorialspoint
tutorialspoint.com › java › java_foreach_loop.htm
Java - for each Loop
June 17, 2025 - Java Vs. C++ ... A for each loop is a special repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.
🌐
W3Schools
w3schools.com › java › java_for_loop.asp
Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop: for (statement 1; statement 2; statement 3) { // code block to be executed } Statement 1 is executed (one time) before the ...
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit7-Arrays › topic-7-3-arrays-with-foreach.html
7.3. Enhanced For-Loop (For-Each) for Arrays — CS Java
To set up a for-each loop, use for (type variable : arrayname) where the type is the type for elements in the array, and read it as “for each variable value in arrayname”. for (type item: array) { //statements using item; } See the examples below in Java that loop through an int and a String ...
🌐
Sentry
sentry.io › sentry answers › java › java for-each loops
Java for-each loops | Sentry
November 11, 2011 - If the object to be looped through is an array, the second loop will be used. This allows us to use the same for-each loop syntax for both arrays and iterables. import java.util.ArrayList; import java.util.List; import java.util.Arrays; class Main { public static void main(String[] args) { List<String> productsList = new ArrayList<>(); productsList.add("Coffee"); productsList.add("Tea"); productsList.add("Chocolate Bar"); String[] productsArray = new String[]{"Coffee", "Tea", "Chocolate Bar"}; for (String product : productsList) { System.out.println(product); } for (String product : productsArray) { System.out.println(product); } // both for loops will produce the same output } }
🌐
Upgrad
upgrad.com › home › blog › software development › for-each loop in java [with coding examples]
For-Each Loop in Java [With Coding Examples] | upGrad blog
January 11, 2023 - It uses the same keyword ‘for’ as in for loop to iterate in collecting items, such as an array. In a for-each loop, there is no need to initialize the loop counter variable. Instead, a variable is declared along with the array name. To get more understanding of its usage, check the syntax of the for-each loop in Java.
🌐
How to do in Java
howtodoinjava.com › home › java flow control › enhanced for loop
Enhanced for (for-each) loop in Java
January 2, 2023 - Since Java 1.5, the for-each loop or enhanced for loop is a concise way to iterate over the elements of an array and a Collection.
🌐
GeeksforGeeks
geeksforgeeks.org › java › loops-in-java
Java Loops - GeeksforGeeks
This loop is used to iterate over arrays or collections. Example: The below Java program demonstrates an Enhanced for loop (for each loop) to iterate through an array and print names.
Published   August 10, 2025