Home > Back-end >  Does for each loop modify the array? I read that it doesn't. However my program is. Pls explain
Does for each loop modify the array? I read that it doesn't. However my program is. Pls explain

Time:12-02

Here is the code that I am testing. My string array a showing modified array elements as dogs, cats, turtles.

String[] a = {"dog", "cat", "turtle"};
System.out.println(java.util.Arrays.toString(a));//line
int i1= 0;
for (String j : a) {
    a[i1]=j "s";
    if (i1 < 2) {
        i1  ;
    }
    System.out.println(i1);
    System.out.println(a[i1]);
}  
System.out.println();
System.out.println(java.util.Arrays.toString(a));//line

output

[dog, cat, turtle]
[dogs, cats, turtles]

CodePudding user response:

The for-loop on it's own isn't modifying anything just reading the Object, but you are modifying it with a[i1]=j "s";. You can modify any public object anywhere in your code as long as you're in the correct scope and it isn't a final.

CodePudding user response:

You are modifying your own array by concatenating s to it. Try doing this

String[] a = {"dog", "cat", "turtle"};
System.out.println(java.util.Arrays.toString(a));//line
int i1= 0;
for (String j : a) {
 a[i1]=j;
 if (i1 < 2) {
    i1  ;
 }
System.out.println(i1);
System.out.println(a[i1]);
}  
System.out.println();
System.out.println(java.util.Arrays.toString(a));//line
  •  Tags:  
  • java
  • Related