2

In the for each loop, the output is 6. However, I thought that the output would be 0 since, at least for one dimensional arrays, for each loops only traverse arrays. How is "g" being edited if "f" is only a local variable in the loop?

int[][] g = new int[7][7];

for(int[] f : g) {
    for(int h = 0; h < f.length; h++)
        f[h] = 6;
}

System.out.println(g[4][6]);
Makoto
  • 104,088
  • 27
  • 192
  • 230
Toby L.
  • 361
  • 1
  • 3
  • 8

1 Answers1

2

Even though Java is pass-by-value, if the values you pass are references to mutable data types, they can be mutated.

As you know, f is the value that you're iterating over in an enhanced-for loop, but it represents each element contained inside of your two-dimensional array g.

In this scenario, it's your int[] that is mutable. You are actively editing the values in your two-dimensional array to another value entirely.

Community
  • 1
  • 1
Makoto
  • 104,088
  • 27
  • 192
  • 230