Reassigning objects in Java with new

java

Solution

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`.

Problem

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?

Original source