+ 2

what happens when you assign one object to another object ??

When you assign one object reference variable to another object reference variable, is this creat just a copy of the object ? Or am i wrong ? plz help 😭

27th Aug 2017, 6:43 PM
Shade96
Shade96 - avatar
4 ответов
+ 6
It assigns the reference of the Object. In other words, both variables 'point' to the same Object. For example/ int [] a = new int[5]; int [] b = a; b and a now 'point' to the same array. So, if I do: b[0] = 3; Variable 'a' 'points' to: {3,0,0,0,0} Variable 'b' 'points' to: {3,0,0,0,0} and If I also do: a[1] = 15. a: {3,15,0,0,0} b: {3,15,0,0,0} This is also referred to as a 'shallow copy'.
27th Aug 2017, 6:55 PM
Rrestoring faith
Rrestoring faith - avatar
+ 6
consider this example, Test t1 = new Test(); Test t2 = t1; Here t1 is reference variable which contain the address of test object. t2 is another reference variable. Now, t2 is initialised with t1, it means both t1 and t2 are referring same object. So no duplicate object is created, nor it allocates extra memory. Any changes made in t1 or t2 will reflect in other. for example, t1.i=1 print(t1.i); // it will print 1 print(t2.i);//it will print 1 t2.i=2 print(t1.i); // it will print 2 print(t2.i);//it will print 2 Hope this helps :)
27th Aug 2017, 7:15 PM
shadab gada
+ 2
Ua most welcomed
27th Aug 2017, 7:21 PM
shadab gada
+ 1
Thankkk youuuuuu very much
27th Aug 2017, 7:18 PM
Shade96
Shade96 - avatar