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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With