abhishake abhishake - 1 month ago 7x
Java Question

Confusing java - enthuware ques. about array

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

True / False

Answer provided is true

class Test{
public static int[ ] getArray() {  return null;  }
public static void main(String[] args){
int index = 1;
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 ...


What does it mean?


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