Reference Variable - Notes by Shariq SP

Reference Variable in Java

A reference variable in Java holds the memory address (reference) of an object rather than the actual object itself. It allows us to access and manipulate objects through their references. Let's delve into why we need reference variables, what they can do, syntax, examples, important notes, interview questions, and MCQs.

Why Do We Need Reference Variables?

In Java, objects are created dynamically using the new keyword. Reference variables are necessary to store the memory address of these objects, enabling us to work with them in our code.

What Can Reference Variables Do?

  • Reference variables can be used to access the attributes and invoke methods of objects.
  • They enable passing objects as arguments to methods and returning objects from methods.
  • They facilitate object manipulation, such as assignment, comparison, and passing to constructors.

Syntax and Examples

Syntax for declaring a reference variable:

ClassName referenceVariable;

Examples:

Car myCar; // Declaring a reference variable of type Car
        Person person; // Declaring a reference variable of type Person
        Animal animal; // Declaring a reference variable of type Animal

Important Notes

  • Reference variables are initialized with null by default if not explicitly assigned.
  • They only hold the memory address of an object and do not contain the object's data.
  • Assigning one reference variable to another copies the memory address, not the object itself.

Interview-Based Questions

  1. What is a reference variable in Java?
  2. How are reference variables different from primitive variables?
  3. Explain the syntax for declaring a reference variable.
  4. What is the default value of a reference variable?
  5. How do you assign one reference variable to another?

Multiple Choice Questions (MCQs)

  1. What does a reference variable in Java store?
    1. Actual object
    2. Memory address of an object
    3. Primitive value
    4. Method
  2. What is the default value of a reference variable?
    1. 0
    2. null
    3. 1
    4. true
  3. Which keyword is used to declare a reference variable?
    1. new
    2. this
    3. class
    4. void
  4. What does assigning one reference variable to another do?
    1. Copies the object
    2. Copies the memory address
    3. Destroys the object
    4. Throws an error