Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassigning objects in Java with new

Tags:

java

This is a noob question regarding memory allocation in Java. I want to know if it is "problematic" to have the following reassignemnts:

For eg.

byte[] b = new byte[10];

..

b = new byte[20]

....

b = new byte[4]

Will this erase the stack and allocate new memory? Can we re-size the variable/object and re-dimension it this way?

like image 538
user907810 Avatar asked Apr 25 '14 09:04

user907810


People also ask

Can we assign one object to another?

If we use the assignment operator to assign an object reference to another reference variable then it will point to the same address location of the old object and no new copy of the object will be created. Due to this any changes in the reference variable will be reflected in the original object.

Can we assign one object to another in Java?

We can copy the values of one object to another using many ways like : Using clone() method of an object class. Using constructor. By assigning the values of one object to another.

How do you change the type of an object in Java?

In Java, you cannot change the class (the type) of an object. That is not possible. You may assign objects of different classes to the same variable. Naturally, you can only assign objects of the same class of the variable or any of its subclasses.


1 Answers

Will this erase the stack and allocate new memory?

Yes, older objects will be GCed if they don't have any live reference.

Can we re-size the variable/object and re-dimension it this way?

No, Java arrays can't grow dynamically. Their size are always fixed.

If it's other object, you can change the state of the object. For Ex : ArrayList, You can change the size of a list after you create it.

Probably just an additional question. If this is only allocating new memory and the old one taken care of by GC, is it ok to do the following:

MyObject myobject = new MyObject(byte[20])
... 
myobject= new MyObject(byte[10]);

Yes, It's perfectly correct. You are re assigning a new object to a older reference myobject.

like image 130
Abimaran Kugathasan Avatar answered Oct 21 '22 21:10

Abimaran Kugathasan