Java quiz 39: References to the objects

<< Java Quizzes   Green = Easy,  Blue = Normal,  Red = Hard
 Q25   Q26   Q27   Q28   Q29   Q30   Q31   Q32   Q33   Q34   Q35   Q36   Q37   Q38   Q39 
 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.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.




Sar Maroof is graduated from HBO Amsterdam "higher professional education". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer for several big as well as small companies and later as a freelancer. He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

 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 *

Sarmaroof © 2017