Java OCA OCP Practice Question 1532

Question

Consider the following class...

public class Main {
   public static void main (String [] args){
      int [] a =  { 1, 2, 3, 4  };
      int [] b =  { 2, 3, 1, 0  };
      System.out.println ( a  [  (a = b)[3] ] );
    }
}

What will it print when compiled and run ?

Select 1 option

  • A. It will not compile.
  • B. It will throw ArrayIndexOutOfBoundsException when run.
  • C. It will print 1.
  • D. It will print 3.
  • E. It will print 4


Correct Option is  : C

Note

In an array access, the expression to the left of the brackets appears to be fully evaluated before any part of the expression within the brackets is evaluated.

In the expression a [(a=b)[3]], the expression a is fully evaluated before the expression (a=b)[3]; this means that the original value of a is fetched and remembered while the expression (a=b)[3] is evaluated.

So, it is actually a[0] = 1.




PreviousNext

Related