Java OCA OCP Practice Question 1455

Question

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

public class Main{ 
  public static void main (String args [] ){ 
    Object a, b, c ; /*from w  w  w . j a v  a  2 s.  c  om*/
    a = new String ("A"); 
    b = new String ("B"); 
    c = a; 
    a = b; 
    System.out.println (""+c); 
   } 
} 

Select 1 option

  • A. The program will print java.lang.String@XXX, where XXX is the memory location of the object a.
  • B. The program will print A
  • C. The program will print B
  • D. The program will not compile as a,b and c are of type Object.
  • E. The program will print java.lang.String@XXX, where XXX is the hash code of the object a.


Correct Option is  : B

Note

The variables a, b and c contain references to actual objects.

Assigning to a reference only changes the reference value, and not the object value.

when c = a is executed c starts pointing to the string object containing A.

When a = b is executed, a starts pointing to the string object containing B but the object containing A still remains same and c still points to it.

So the program prints A and not B.




PreviousNext

Related