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

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

Susan Sarandon
Release: 2024-12-21 11:54:14
Original
837 people have browsed it

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

Diving into the Iteration Dilemma: Why Foreach Loop Assignments Don't Alter Underlying Data

Despite the intuitive appeal of directly modifying elements within a foreach loop, as seen in this Java snippet:

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

for(char c : array)
{
 if (c== 'o')
     c = 'a'; 
}
System.out.println(new String(array)); //Unexpected result: "boss"
Copy after login

the code surprisingly yields "boss" instead of the expected "bass."

Unveiling the Copy

The key to understanding this paradox lies in the nature of the iteration variable "c." Contrary to popular belief, "c" represents a mere copy of the array element at hand. Modifying "c" has no bearing on the original array contents.

Array Modification Demystified

To genuinely alter the array, explicit intervention is necessary:

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

Here, the code accesses and modifies the actual array elements, resulting in the array being updated to reflect the desired changes.

Understanding JLS Interpretation

The Java Language Specification (JLS) interprets the original code as equivalent to:

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

This decomposition emphasizes that "c" is merely a copy that cannot influence the array.

In essence, foreach loops provide a streamlined means of iterating over collections without interfering with their underlying structure. Direct array modification requires explicitly working with the array index and elements.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template