Java quiz 37: Handling three object references

  Quizzes     Assignments     Puzzles     Easy exercises     Required knowledge  
< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
Select    31   32   33   34   35   36   37   38   39   40   By title 
>

 

Java quiz 37: Handling three object references

Level: Normal

What is the output of the following code?

public class MyClass
{
  public static void main(String[] args)
  {
    Object o1 = new Object();
    Object o2 = new Object();
    Object o3 = new Object();
    System.out.print(o1.equals(o1 = o2)); 
    System.out.print(", ");
    System.out.print(o2.equals(o3 = o1)); 
    System.out.print(", ");
    System.out.print(o1 == o3); 
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “true, true, true” to the standard output.
b. This program writes “false, false, false” to the standard output.
c. This program writes “true, false, false” to the standard output.
d. This program writes “false, true, false” to the standard output.
e. This program writes “false, true, true” to the standard output.
f. Illegal at compile time.
g. Illegal at run time.

Answer explanation

  1. In the statement ‘System.out.print(o1.equals(o1 = o2));’  the value of o1 is evaluated before calling the method, then the operands are evaluated, so o1 becomes o2. The result of o1 equals to o2 is false.
  2. In the statement ‘System.out.print(o2.equals(o3 = o1));’ the value of o2 is evaluated before calling the method. Then the operands are evaluated, so o3 refers to o1. In the first statement o1 and o2 refer to the same object. Therefore, the result of o2 equals to o1 is true.
  3. Now o1, o2 and o3 are references to the same object. In the third statement o1 equals to o3 is also true.

The correct answer is: e.




Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *