2

I am currently reading Downey's Think Java which recently introduced the enhanced for loop. It was mentioned that the enhanced for loop doesn't take element indices into consideration when it's traversing the array. I thought that this wouldn't inhibit something like the following method from working:

    public static double[] powArray(double[] a) {
        for (double value : a) {
            value = Math.pow(value, 2.0);
        }
        return a;
    }                 

However, it seems that it does (the rest of the code to which this belongs seems fine). Just to note, this method ends up returning the same array when I run the following:

    System.out.println(Arrays.toString(powArray(a)));

I suppose I'm having trouble understanding whether the issue here lies in how I'm handling the enhanced for loop or array references. Thanks in advance!

3 Answers3

4

Look in JLS Sec 14.14.2, where it gives the equivalent form of the enhanced for loop over an array:

for ( {VariableModifier} TargetType Identifier : Expression ) Statement

[is equivalent to, if Expression is an array type]

T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
    {VariableModifier} TargetType Identifier = #a[#i];
    Statement
}

So, your loop is converted by the compiler to look like this:

double[] a = arr;
for (int i = 0; i < a.length; i++) {
  double value = a[i];
  value = Math.pow(value, 2.0);
}

You are squaring value, but that value isn't ever written back to arr (or a, even).

If you want to modify the array elements, you have to use a basic for loop explicitly:

for (int i = 0; i < a.length; i++) {
  a[i] = Math.pow(a[i], 2.0);
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

A working mental model of how the JVM works will help.

The value of an array variable is a reference.

The value of a double variable is a double.

On each iteration of the loop, your value variable gets an element of the array copied into it.

When you do

value = Math.pow(value, 2.0);

you are just changing the value of the value variable (the copy). This has no effect on the array because the value from the array was copied into the value of value and it was that value that is changed by the assignment.

BPS
  • 1,606
  • 20
  • 37
0

You should but value back to the array or just create new array, store all pow values to it and return this array.