Java OCA OCP Practice Question 1730

Question

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

public class MyClass {
  public static void main(String[] args) {
    String a, b, c;/*from  ww  w.  ja v  a2  s  .c  om*/
    c = new String("mouse");
    a = new String("cat");
    b = a;
    a = new String("dog");
    c = b;

    System.out.println(c);
  }
}

Select the one correct answer.

  • (a) The program will fail to compile.
  • (b) The program will print mouse, when run.
  • (c) The program will print cat, when run.
  • (d) The program will print dog, when run.
  • (e) The program will randomly print either cat or dog, when run.


(c)

Note

Strings are objects.

The variables a, b, and c are references that can denote such objects.

Assigning to a reference only changes the reference value.

It does not create a copy of the source object or change the object denoted by the old reference value in the target reference.

In other words, assignment to references only affects which object the target reference denotes.

The reference value of the "cat" object is first assigned to a, then to b, and later to c.

The program prints the string denoted by c, "cat".




PreviousNext

Related