By design the for each variable 'x' (in this case) is not meant to be assigned to. I'm surprised that it even compiles fine.

String[] currentState = new String[answer.length()]; 
for (String x : currentState) { 
    x = "_"; // x is not a reference to some element of currentState 
}

The following code maybe shows what you're in effect are doing. Note that this is not how enumerations work but it exemplifies why you can't assign 'x'. It's a copy of the element at location 'i'. (Edit: note that the element is a reference type, as such it's a copy of that reference, assignment to that copy does not update the same memory location i.e. the element at location 'i')

String[] currentState = new String[answer.length()]; 
for (int i = 0; i < answer.length(); i++) { 
    String x = currentState[i];
    x = "_";
}
Answer from John Leidegren on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_foreach_loop.asp
Java For-Each Loop
The for-each loop is simpler and more readable than a regular for loop, since you don't need a counter (like i < array.length). The following example prints all elements in the cars array:
🌐
GeeksforGeeks
geeksforgeeks.org › java › for-each-loop-in-java
For-Each Loop in Java - GeeksforGeeks
2 weeks ago - The for-each loop in Java (introduced in Java 5) provides a simple, readable way to iterate over arrays and collections without using indexes.
Discussions

foreach - Understanding for each loop in Java - Stack Overflow
Why doesn't assigning to the iteration variable in a foreach loop change the underlying data? More on stackoverflow.com
🌐 stackoverflow.com
Java 8 Iterable.forEach() vs foreach loop - Stack Overflow
Traditional for-each loops will certainly stay good practice (to avoid the overused term "best practice") in Java. But this doesn't mean, that Iterable#forEach should be considered bad practice or bad style. More on stackoverflow.com
🌐 stackoverflow.com
When to use for-each Loop, while loop, Iterator Object?
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
10
7
November 7, 2021
[Java] Simple explanation of for each loops
Alright, so a forEach loop is simply some syntactical sugar. Something that makes a common problem or action easier to do. Easier can mean easier in terms of writing it, but also relates to code readability. Anyways, so a normal for loop takes the three conditions that you have stated: for(int i = 0; i < condition; i++ ) { } So I will have a counter here. A super common thing to use a for loop for, is to loop through the contents of an array. So: for(int i = 0; i < myArray.length; i++) { myElement = myArray[i]; } So, at the i-th index, get the element there, and then let's do something with it. But that's a lot of boilerplate ( read: Lot of typing to do something so basic and common ). So, the solution is to use the forEach loop. So we use the syntax: for ( myObject object : myArray ) { } This seems confusing at first, but break it down. All it is saying, in English is: I would like to loop through every element of myArray. During each loop, I would like the current element I am at to be referenced with the variable object which is of type myObject You are now allowed to work with this. But myObject and object are placeholders, and they aren't the easiest to understand. So I will write you a small program that will sum all of the numbers in an array. int integerArray[] = {5, 10, 15, 20, 25, 30} // With normal for loop int count = 0; for( int i = 0; i < integerArray.length; i++){ int currentInteger = integerArray[i]; count += currentInteger; } // Now, with a for each loop int count = 0; for ( int currentInteger : integerArray ) { count += currentInteger; } Notice, we skipped a step in the second one because it will loop through with the first element of the array as the name currentInteger, and when it is done adding itself to count, it will go to the next element. We don't keep track of the size, we don't have the count variable, we don't have int i or i++, we simply manipulate the elements located within the array and do what we want. Now, of course under the hood Java is keeping track of where we are, and setting that variable to the next one on each rotation, but that's what syntactical sugar is all about. We focus on writing code, not boilerplate, and having a for each loop let's us worry about the actual logic, not correctly initializing a for loop and keeping track of indices. More on reddit.com
🌐 r/learnprogramming
7
1
November 2, 2015
🌐
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.
Top answer
1 of 6
31

By design the for each variable 'x' (in this case) is not meant to be assigned to. I'm surprised that it even compiles fine.

String[] currentState = new String[answer.length()]; 
for (String x : currentState) { 
    x = "_"; // x is not a reference to some element of currentState 
}

The following code maybe shows what you're in effect are doing. Note that this is not how enumerations work but it exemplifies why you can't assign 'x'. It's a copy of the element at location 'i'. (Edit: note that the element is a reference type, as such it's a copy of that reference, assignment to that copy does not update the same memory location i.e. the element at location 'i')

String[] currentState = new String[answer.length()]; 
for (int i = 0; i < answer.length(); i++) { 
    String x = currentState[i];
    x = "_";
}
2 of 6
9

Original code:

String currentState = new String[answer.length()];

for(String x : currentState) 
{ 
    x = "_"; 
}

Rewritten code:

String currentState = new String[answer.length()];

for(int i = 0; i < currentState.length; i++) 
{ 
    String x;

    x = currentState[i];
    x = "_"; 
}

How I would write the code:

String currentState = new String[answer.length()];

for(final String x : currentState) 
{ 
    x = "_";   // compiler error
}

Rewritten code with the error:

String currentState = new String[answer.length()];

for(int i = 0; i < currentState.length; i++) 
{ 
    final String x;

    x = currentState[i];
    x = "_";   // compiler error
}

Making the variables final highlights when you do things like this (it is a common beginner mistake). Try to make all of your variables final (instance, class, arguments, exceptions in catch. etc...) - only make them non-final if you really have to change them. You should find that 90%-95% of your variables are final (beginners will wind up with 20%-50% when they start doing this).

🌐
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).
Top answer
1 of 8
653

The better practice is to use for-each. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach() has at least the following deficiencies:

  • Can't use non-final variables. So, code like the following can't be turned into a forEach lambda:
Object prev = null;
for(Object curr : list)
{
    if( prev != null )
        foo(prev, curr);
    prev = curr;
}
  • Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch or Throwables.propagate(). But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()

  • Limited flow-control. A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."

  • Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.

  • Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.

  • If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).

  • Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.

  • Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.

  • Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).

As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.

Particularly offensive to me is the fact that Stream does not implement Iterable (despite actually having method iterator) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable.

That said, forEach() is useful for the following:

  • Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList() was atomic with respect to things like get or set, but was not thread-safe when iterating.

  • Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.

  • Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)

  • Calling a single function more cleanly by using forEach() and a method reference argument (ie, list.forEach (obj::someMethod)). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.

Articles I used for reference:

  • Everything about Java 8
  • Iteration Inside and Out (as pointed out by another poster)

EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).

2 of 8
174

The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)

  • The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential

  • If you want your loop to be executed in parallel you could simply write

     joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
    

    You will have to write some extra code for thread handling etc.

Note: For my answer I assumed joins implementing the java.util.Stream interface. If joins implements only the java.util.Iterable interface this is no longer true.

Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › guide to the java foreach loop
Guide to the Java forEach Loop | Baeldung
June 17, 2025 - This interface has a new API starting with Java 8: ... Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”
🌐
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.
🌐
Runestone Academy
runestone.academy › ns › books › published › apcsareview › 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 ...
🌐
IONOS
ionos.com › digital guide › websites › web development › java for-each loop
How to use for-each loops in Java - IONOS
November 3, 2023 - In each iteration, you can perform automatic ma­nip­u­la­tions with common Java operators without having to write a separate statement for each element. In contrast to the for loop in Java, when you use the for-each Java loop, you don’t need to consider the index or size of the array.
🌐
Sentry
sentry.io › sentry answers › java › java for-each loops
Java for-each loops | Sentry
December 15, 2023 - Note that the iteration variable in a for-each loop merely contains a copy of the value at that point in the list and reassigning it will not change the underlying list. For example: String[] products = new String[]{"Coffee", "Tea", "Chocolate Bar"}; for (String product : products) { if (product == "Chocolate Bar") { product = "Granola Bar"; } } System.out.println(Arrays.toString(products)); // will print ["Coffee", "Tea", "Chocolate Bar"] Sentry Blog Exception Handling in Java (with Real Examples) (opens in a new tab)
🌐
TutorOcean
tutorocean.com › questions-answers › can-someone-please-explain-the-difference-between-a-for-loop-and-a-for-each-loop
Can someone please explain the difference between a for ...
Sorry, your browser does not support JavaScript! If possible, please enable JavaScript on your browser or switch to another browser (Chrome, Firefox, Safari) · ‌ ‌ ‌ ‌ ‌ · ‌ ‌ ‌ ‌
🌐
Tutorialspoint
tutorialspoint.com › java › java_foreach_loop.htm
Java - for each Loop
Here we're creating an List of integers as numbers and initialized it some values. Then using foreach loop, each number is printed. import java.util.Arrays; import java.util.List; public class Test { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50); for(Integer x : numbers ) { System.out.print( x ); System.out.print(","); } } }
🌐
Udemy
blog.udemy.com › home › how to use the for each loop in java with arrays
How to Use the for each Loop in Java with Arrays - Udemy Blog
December 4, 2019 - Now, if you have noticed all the above examples, they are generally used to manipulate integers. What does one do when they have to work with iteration over arrays? To answer this question, in Java 5 was introduced the “For-each” loop. This loop can be used very well with iteration over arrays and other such collections.
🌐
Reddit
reddit.com › r/javahelp › when to use for-each loop, while loop, iterator object?
r/javahelp on Reddit: When to use for-each Loop, while loop, Iterator Object?
November 7, 2021 -

Basically in the title. I have a hard time deciding which one to use to iterate over a collection. I am pretty sure that for-each is for definite iteration (i.e. when you know exactly how many elements you want to iterate across), while is for indefinite iteration (i.e. you do not know where the element that you're looking for is in the collection), and I have absolutely no idea about when you should use an Iterator Object. Could somebody please be kind enough to explain the difference between the three?

🌐
Reddit
reddit.com › r/learnprogramming › [java] simple explanation of for each loops
r/learnprogramming on Reddit: [Java] Simple explanation of for each loops
November 2, 2015 -

Hi, every example I see of for each loops I see confuses me. I know for for loops it is: for(begining counter; do while counter is less, greater or equal to n; increase or decrease counter) . I was hoping someone could help explain how for each loops work and there applications instead of for loops. Sorry if this is a basic question, other answers I found in the java documentation and on stackoverflow didn't seem to help me.

Edit: I understand now! Thank you guys so much!

Top answer
1 of 2
2
Alright, so a forEach loop is simply some syntactical sugar. Something that makes a common problem or action easier to do. Easier can mean easier in terms of writing it, but also relates to code readability. Anyways, so a normal for loop takes the three conditions that you have stated: for(int i = 0; i < condition; i++ ) { } So I will have a counter here. A super common thing to use a for loop for, is to loop through the contents of an array. So: for(int i = 0; i < myArray.length; i++) { myElement = myArray[i]; } So, at the i-th index, get the element there, and then let's do something with it. But that's a lot of boilerplate ( read: Lot of typing to do something so basic and common ). So, the solution is to use the forEach loop. So we use the syntax: for ( myObject object : myArray ) { } This seems confusing at first, but break it down. All it is saying, in English is: I would like to loop through every element of myArray. During each loop, I would like the current element I am at to be referenced with the variable object which is of type myObject You are now allowed to work with this. But myObject and object are placeholders, and they aren't the easiest to understand. So I will write you a small program that will sum all of the numbers in an array. int integerArray[] = {5, 10, 15, 20, 25, 30} // With normal for loop int count = 0; for( int i = 0; i < integerArray.length; i++){ int currentInteger = integerArray[i]; count += currentInteger; } // Now, with a for each loop int count = 0; for ( int currentInteger : integerArray ) { count += currentInteger; } Notice, we skipped a step in the second one because it will loop through with the first element of the array as the name currentInteger, and when it is done adding itself to count, it will go to the next element. We don't keep track of the size, we don't have the count variable, we don't have int i or i++, we simply manipulate the elements located within the array and do what we want. Now, of course under the hood Java is keeping track of where we are, and setting that variable to the next one on each rotation, but that's what syntactical sugar is all about. We focus on writing code, not boilerplate, and having a for each loop let's us worry about the actual logic, not correctly initializing a for loop and keeping track of indices.
2 of 2
1
Say you have an array of things. Let's call it int[] myArray and let's say we put 1, 2, 3 inside of it. And you want to print each thing inside of myArray. So we start at the beginning of myArray and start walking towards the end. Each step we take, we take the number at that step, set it to some variable i and then print i. You could write a foreach loop like this: for (int i : myArray) { System.out.println(i); } What this does is it goes through myArray, starting at the beginning, and it: Sets i to the current element inside of myArray. Does the stuff in the body (the system.out.print...) So it basically does the stuff in the body for each thing inside of the array. First, i is equal to 1, and it prints 1. Then, i is equal to 2, and it prints 2. Finally, i is equal to 3, and it prints 3.
🌐
Quora
quora.com › Are-there-any-advantages-of-using-forEach-from-Java-8-instead-of-a-forEach-loop-from-Java-5-Java-development
Are there any advantages of using forEach(..) from Java 8 instead of a forEach loop from Java 5 (Java development)? - Quora
Answer (1 of 4): Yes, there are distinct advantages. However, to get those advantages, your code needs to use some of the other functionality of Java 8. I was in a rather complicated but also very interesting talk at a conference, where one of the Java just-in-time compiler developers spoke abou...
🌐
Scaler
scaler.com › home › topics › java › for-each loop in java
For-each Loop in Java - Scaler Topics
March 22, 2024 - 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.