Introduction
Starting by taking two variables var1 and var2 of integer type, such as
int var1 = 5;
int var2 = var1;
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
100
100
30
30
11
30
90
90
90
Join the conversation! Your thoughts help the community grow.