-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}

2
  • 1
    Your increment is not after the return statement. It is inside the return statement. Commented Jun 12, 2018 at 9: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. Commented Jun 12, 2018 at 9:47

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.