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
- What is a reference variable in Java?
- How are reference variables different from primitive variables?
- Explain the syntax for declaring a reference variable.
- What is the default value of a reference variable?
- How do you assign one reference variable to another?
Multiple Choice Questions (MCQs)
- What does a reference variable in Java store?
- Actual object
- Memory address of an object
- Primitive value
- Method
- What is the default value of a reference variable?
- 0
null
- 1
true
- Which keyword is used to declare a reference variable?
new
this
class
void
- What does assigning one reference variable to another do?
- Copies the object
- Copies the memory address
- Destroys the object
- Throws an error