-2

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}

Nick Sm
  • 35
  • 1
  • 5
  • 1
    Your increment is not _after_ the return statement. It is _inside_ the return statement. – khelwood Jun 12 '18 at 09:45
  • Is there a question in here? Clearly what seems logical to you is not the case. `variable++` is an expression that yields the value that the variable had before incrementing, and also increments the variable, *before the expression completes*. – Erwin Bolwidt Jun 12 '18 at 09:47

2 Answers2

4

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;
assylias
  • 321,522
  • 82
  • 660
  • 783
0

The array[0]++ is inclusive in the return statement. Hence the incremented value is stored in array[0] (i.e array[0] = 1) Don't confuse yourself thinking that increment will take after return statement as it is post-increment

Shubham Sahu
  • 1
  • 1
  • 2