Java quiz 39: References to the objects

  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   41   By title 
>

A simple example to make it clear how object references work?

Java quiz 39: References to the objects

Level: Normal

What is the output of the following code?

public class Laptop
{
  String brand;
  int hardDisk;
  
  Laptop(String brand, int hardDisk)
  {
    this.brand = brand;
    this.hardDisk = hardDisk;
  }
  public static void main(String[] args)
  {
    Laptop laptop1 = new Laptop("Dell", 500);
    Laptop laptop2 = new Laptop("HP", 300);
    laptop1 = laptop2;
    Laptop laptop3 = laptop1;
    System.out.print(laptop3.brand + ", ");
    System.out.print(laptop1.hardDisk);
  }
}
Author: Sar Maroof

Select the correct answer.

a. This program writes “HP, 500” to the standard output.
b. This program writes “Dell, 500” to the standard output.
c. This program writes “Dell, 300” to the standard output.
d. This program writes “null, 300” to the standard output.
e. This program writes “HP, 300” to the standard output.

Answer explanation

  1. The statement laptop1 = laptop2; refers laptop1 to laptop2.
  2. The statement Laptop laptop3 = laptop1; refers laptop3 to laptop1 and at last to laptop2.
  3. Therefore laptop3.brand writes HP to the standard outpu and the statement laptop1.hardDisk writes 300 to the standard output.

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 *