Introduction
Starting by taking two variables var1 and var2 of integer type, such as
int var1 = 5;
int var2 = var1;
Simply, 5 is assigned to var1 and the value of var1 is assigned to var2.
Changing the value of var2 as
var2 = 10;
When you print var1 and var2, you get 5 and 10 as output respectively.
But, in case of object reference variables, you may marvel, when assigning one
object reference variable to another. To understand, what's the thing I am
trying to be pointed to, review the simple java program written below
Code:
- public class MyJavaClass
- {
- public static void main(String[] args)
- {
- Demo obj = new Demo();
- obj.a = 30;
- obj.b = 50;
- Demo obj1 = obj;
- System.out.println(obj.add(obj.a, obj.b));
- System.out.println(obj.add(obj1.a, obj1.b));
- obj.a = 50;
- obj.b = 50;
- System.out.println(obj.add(obj.a, obj.b));
- System.out.println(obj.add(obj1.a, obj1.b));
- obj1.a = 10;
- obj1.b = 20;
- System.out.println(obj.add(obj.a, obj.b));
- System.out.println(obj.add(obj1.a, obj1.b));
- Demo obj2 = new Demo();
- obj2.a = 5;
- obj2.b = 6;
- System.out.println(obj.add(obj2.a, obj2.b));
- obj2 = obj1;
- System.out.println(obj.add(obj2.a, obj2.b));
- obj2.a = 15;
- obj2.b = 75;
- System.out.println(obj.add(obj.a, obj.b));
- System.out.println(obj.add(obj1.a, obj1.b));
- System.out.println(obj.add(obj2.a, obj2.b));
- }
- }
- class Demo
- {
- int a, b;
- public int add(int a, int b)
- {
- return a + b;
- }
- }
80
80
100
100
30
30
11
30
90
90
90
You can observe that after assigning one object reference
variable to another object reference variable. The output of "a+b" is same
whether you are using any of object reference variable.
This happens, because the assignment of one object reference
variable to another didn't create any memory, they will refer to the same
object. In other words, any copy of the object is not created, but the copy of the reference is created. For example,
obj1 = obj;
The above line of code just defines that obj1 is referring
to the object, obj is referring. So, when you make changes to object using obj1
will also affect the object, b1 is referring because they are referring to the
same object.