What is a reference variable in java?
- Reference variable in java is a class type variable.
- In other words, declaring a variable along with class name is nothing but a reference variable.
- Reference variable stores the address of an object which acts as a way to access an object
- By using reference variable we can access non static members of the class.
- If no object is passed into the reference variable then by default null value will be stored .
Example
class Demo {
int a=20;
void test(){
System.out.println("Test Method");
}
}
class MainApp{
public static void main(String[] args) {
//Creating object for class Demo
Demo d1=new Demo();
//printing reference variable
System.out.println(d1);
//Accessing non-static members of Demo class using reference variable
System.out.println("A value is "+d1.a);
d1.test();
}
}
Output:
ReferenceVariable.Demo@1b28cdfa A value is 20 Test Method
To understand the above example let us have a look at the following points:
- When we create an object for the class Demo, the address of object new Demo() gets stored into the reference variable d1.
- When we print the reference variable the output contains fully qualified name of the class along with the hexadecimal value(hash code). In this case, it is ReferenceVariable.Demo@1b28cdfa.
- In the next step, we have accessed variable ‘a’ and method test() from demo class by using reference variable d1.
Is it possible to create an object with multiple references?
- It is possible to create a single object with multiple reference variables.
- It means we can copy address of one variable into another variable.
- If we create object with multiple references then all reference variables will be having same address.
Example:
class Sample {
void display(){
System.out.println("Display Method");
}
}
class MainApp1{
public static void main(String[] args) {
Sample s1=new Sample();
//Creating a copy of reference variable for the same object
Sample s2=s1;
//comparing the address for both reference variable
System.out.println(s1==s2);
}
}
Output:
true

