Java OCA OCP Practice Question 1921

Question

What will be the result of attempting to compile and run the following class?

public class Main{
    public static void main (String args [] ){
       int i = 1;
       int [] iArr =  {1};
       incr (i) ;//from   w  ww  . ja  v  a 2 s . c om
       incr (iArr) ;
       System.out.println ( "i = " + i + "  iArr [0] = " + iArr  [ 0 ] ) ;
     }
    public static void incr (int n)  { n++ ;  }
    public static void incr (int[] n)  { n  [ 0 ]++ ;  }
}

Select 1 option

A. The code will print i = 1 iArr [0] = 1;
B. The code will print i = 1 iArr [0] = 2;
C. The code will print i = 2 iArr [0] = 1;
D. The code will print i = 2 iArr [0] = 2;
E. The code will not compile.


Correct Option is  : B

Note

Arrays are proper objects and Object references are passed by value.

So the value of reference of iArr is passed to the method incr (int[] i); This method changes the actual value of the int element at 0.




PreviousNext

Related