Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

memory

Assume we have a class:

    class Account {
      String name;
      int ID;
    }

Then

a1 = new Account();

a2 = new Account();

Will create 2 variables that point to 2 memory locations storing 2 instances of class Account.

My question is how Java can know how big these instances are to allocate their memory (Because with String type, we can assign any string to that. For example, a1.name = "Solomon I", a2.name = "Alan". This will lead to different size of each instance)

Memory location is a 'continuous' string of bytes. Therefore, if I have a1 = new Account() then a2 = new Account() => a1's memory location is fixed ('used memory | a1 | a2') so what will happen if I make a1.name a very long string? Will a1's memory location extend to a2's memory location?

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

like image 393
Trung Tran Avatar asked Mar 13 '13 11:03

Trung Tran


2 Answers

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

Therefore, as part of your object, java only needs to "allocate" space for the String reference, plus an int, which are constant in size.

like image 149
vikingsteve Avatar answered Nov 09 '22 03:11

vikingsteve


The object just holds the reference to other object(member variables). So its size will always be fixed. So changing the contents of the referred object will not effect the size of the object referring to it. So you need not worry about the String size and your 'Account' class object will not be effected even if you change the String, as only String reference is stored by the 'Account' class object.

Hope this has helped you.

like image 40
Ankur Shanbhag Avatar answered Nov 09 '22 02:11

Ankur Shanbhag