Home >Java >javaTutorial >Why Doesn't Modifying the Iteration Variable in a Java For-Each Loop Change the Original Array?

Why Doesn't Modifying the Iteration Variable in a Java For-Each Loop Change the Original Array?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 12:11:13778browse

Why Doesn't Modifying the Iteration Variable in a Java For-Each Loop Change the Original Array?

Iteration Variable Assignment in Foreach Loops

In Java, foreach loops provide a concise syntax for iterating over collections. However, a common misconception arises when modifying the iteration variable within the loop. Consider the following code:

String boss = "boss";
char[] array = boss.toCharArray();

for(char c : array) {
    if (c == 'o')
        c = 'a';
}

System.out.println(new String(array)); // Prints "boss"

Why does this code print "boss" instead of the expected "bass"?

To understand this behavior, it's crucial to recognize that foreach loops operate on copies of collection elements, not the elements themselves. The iteration variable, in this case c, is only a local copy of the current element in the array. Modifying c does not modify the original character in the array.

To modify the array elements, you must explicitly access the elements through their index, like so:

for (int i = 0; i < array.length; i++) {
    if (array[i] == 'o') {
        array[i] = 'a';
    }
}

This code assigns the modified character directly to the array element, resulting in the desired output of "bass".

In summary, when working with foreach loops, remember that the iteration variable represents a local copy of the collection element. To modify the underlying data, explicitly access the element through its index and perform the modification directly on the array.

The above is the detailed content of Why Doesn't Modifying the Iteration Variable in a Java For-Each Loop Change the Original Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn