How does Java allocate memory for a new instance (with the String property)?

Suppose we have a class:

class Account { String name; int ID; } 

Then

 a1 = new Account(); a2 = new Account(); 

Creates 2 variables that point to 2 memory cells storing 2 instances of the Account class.

My question is how Java can know how large these instances are for allocating its memory (because with the String type we can assign any string to it. For example, a1.name = "Solomon I", a2.name = "Alan" . This will result in a different size for each instance)

A memory location is a "continuous" string of bytes. Therefore, if I have a1 = new Account() , then a2 = the new memory location Account () => a1 is fixed ('used memory | a1 | a2'), so what happens if I make a1.name a very long line ? Will memory area a1 extend to memory cell a2?

Thank you for reading this, please let me know if I have any misconceptions.

+7
source share
2 answers

name is a reference to String (not the actual string). It will "point" to the String object when it is assigned.

Therefore, as part of your object, java only needs to β€œallocate” space for a reference to String, as well as int, which are constant in size.

+12
source

An object simply contains a reference to another object (member variables). Therefore, its size will always be fixed. Therefore, changing the contents of the specified object will not affect the size of the object referencing it. Therefore, you don’t need to worry about the size of the string, and the object of the Account class will not execute even if you change the String, since only the String object is stored by the object of the Account class.

Hope this helps you.

+1
source

All Articles