Number of objects and links | Java

Consider the following piece of code in Java:

Customer obj1 = new  Customer();  
Customer obj2 = new Customer();  
Customer obj3 = obj2;  
obj3 = obj1;   

      

How many reference variables and objects are created here? The solutions I came across all got confused. Explain, please.

+3


source to share


7 replies


Customer Obj1= new  Customer();  

      

// Customer object is created on the heap and obj1 refers to it

Customer Obj2= new Customer();  

      

// The Customer object is created on the heap and obj2 refers to it

Customer Obj3= Obj2;  

      



// obj3 will refer to the client object created by obj2

 Obj3= Obj1;   

      

// obj3 (the previous reference to cust obj craated by obj2 will be lost) and will now reference the cust obj created by obj1

So I would say 2 objects and 3 ref variables

  • obj1 and obj3 referring to the object created by obj1
  • obj2 refers to an object created by obj2 itself
+2


source


After

Obj3= Obj1;

      



You will have two objects and 3 links. Obj1 and Obj3 will refer to the same object.

+3


source


Although the JLS doesn't prohibit it, AFAIK no JVM uses reference counting, it's too unreliable. Note. C ++ smart pointer uses reference count, but they are very inefficient.

You have up to three references to two different objects.

Note: if your code doesn't do something useful with them, the JVM can optimize that code to zero, in which case you won't have references or objects.

+1


source


Assuming it's custObj2

initialized new

, and from the above snippet, its 3 objects (including custObj2

) and four references (including Obj3

)

0


source


There are three variables and two objects.

0


source


2 objects are created (first 2 lines).

Created 3 reference variables (Obj1, Obj2 and Obj3 are all reference variables.)

The last two lines simply assign references to 2 different Obj3 objects.

0


source


Go through iteratively ...

Customer Obj1= new  Customer();  

      

Created one new object referenced by Obj1

Customer Obj2= new Customer();  

      

Created second object referenced by Obj2

Customer Obj3= custObj2;  

      

Obj3, a reference variable, refers to custObj2

(which doesn't exist in this dataset, suppose it was created earlier?)

Obj3= Obj1; 

      

Obj3 is reassigned to point Obj1.

In the end you have three references: Obj1, Obj2 and Obj3, as well as 2 objects (the first two operators) and finally ambiguous custObj2

... if you want to type Obj2 then ignore this part :)

0


source







All Articles