Java OCA OCP Practice Question 1668

Question

What will be the result of compiling and running the following program?.

public class Main {
  public static void main(String[] args) {
    int a = 0; /*from   w  w  w.j a v  a 2  s  .com*/
    int b = 0;
    int[] bArr = new int[1]; 
    bArr[0] = b;

    inc1(a); 
    inc2(bArr);

    System.out.println("a=" + a + " b=" + b + " bArr[0]=" + bArr[0]);
  }

  public static void inc1(int x) { x++; }

  public static void inc2(int[] x) { x[0]++; }
}

Select the one correct answer.

  • (a) The code will fail to compile, since x[0]++; is not a legal statement.
  • (b) The code will compile and will print "a=1 b=1 bArr[0]=1", when run.
  • (c) The code will compile and will print "a=0 b=1 bArr[0]=1", when run.
  • (d) The code will compile and will print "a=0 b=0 bArr[0]=1", when run.
  • (e) The code will compile and will print "a=0 b=0 bArr[0]=0", when run.


(d)

Note

The variables a and b are local variables that contain primitive values.

When these variables are passed as arguments to another method, the method receives copies of the primitive values in the variables.

The actual variables are unaffected by operations performed on the copies of the primitive values within the called method.

The variable bArr contains a reference value that denotes an array object containing primitive values.

When the variable is passed as a parameter to another method, the method receives a copy of the reference value.

Using this reference value, the method can manipulate the object that the reference value denotes.

This allows the elements in the array object referenced by bArr to be accessed and modified in the method inc2().




PreviousNext

Related