abhishake abhishake - 3 months ago 10
Java Question

Confusing java - enthuware ques. about array

Question: The following class will print 'index = 2' when compiled and run.

Options:
True / False

Answer provided is true

class Test{
public static int[ ] getArray() {  return null;  }
public static void main(String[] args){
int index = 1;
try{
getArray()[index=2]++;
}
catch (Exception e){  }  //empty catch
System.out.println("index = " + index);
}
}


But I am not understanding this part, I've searched a lot but couldn't find a solution ...

getArray()[index=2]++;


What does it mean?

Answer
getArray()[index=2]++;

Can be seen as a group of operations:

  • Invoke getArray() is the first operation done here, see the note.
  • assign the value 2 to the variable index
  • Return 2 from the assignement index = 2
  • retrieve the third element on the array returned by getArray(). Note that here an exception is thrown, so the next operation is not done
  • increment the value of that element by one. This is not done, because an Exception already happened.

Note: The operation getArray() happens before index=2 because of JVMS, as well explained by @fge. Here is possible to find a reference to the JVMS. See in particular example 15.10.4-2:

If evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated

Comments