Search code examples
javareturnincrementorder-of-execution

Java performs the increment operation after return on object references


I have this code :

public class counter {
    public static void main(String[] args){
        double[] array = new double[10];
        for(int i=0;i<array.length;i++) array[i] = i;
        printArray(array);
        double result = doSomething(array);
        printArray(array);
    }
    public static void printArray(double[] arr){
        for(double d : arr) System.out.println(d);
    }
    public static double doSomething(double[] array){
        return array[0]++;
    }
}

I have learned that after the return statement no more code is executed and the increment++ increments the value at the next expression. So it seems logical to me that the the first element of the array array[0] should not be incremented.

However the output array is {1,1,2,3,4,5,6,7,8,9}


Solution

  • after the return statement no more code is executed

    That's correct. But the ++ is not after the return statement, it's part of it.

    Your code is equivalent to:

    int temp = array[0];
    array[0] = temp + 1;
    return temp;