Trung Tran
Trung Tran

Reputation: 229

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

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.

Upvotes: 7

Views: 1832

Answers (2)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

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.

Upvotes: 1

vikingsteve
vikingsteve

Reputation: 40378

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.

Upvotes: 12

Related Questions