How can the JVM allocate memory for objects despite the possibility that they might later grow in size

Consider we have a class Node in java like this:

class Node{
Node prev;
Node next;
}

when we create a new Node (Node sample = new Node();) how does the JVM allocate enough memory for the object. Its size might change in the future. For example, later I can set sample.setPrev(new Node()) and so on. so if JVM considers indexes from 1000 to 2000 in memory for this sample object then it's size might change and the memory index 2001 might not be empty for our use.

2 answers

  • answered 2018-11-08 07:47 htpvl

    The heap memory is used by a java object including:

    • Primitive fields: Integer, String, Float, etc. They have fixed length in memory.
    • Object fields(like your prev and next object),they have 4 bytes for each, just used to store reference only. When you set sample.setPrev(new Node()), your prev will keep a reference to another memory space.

  • answered 2018-11-08 08:06 Raedwald

    All Java objects have a fixed size that is known at the point of construction of the object. No operations your code can perform can cause an object to grow and need more space.

    To understand why that is so, you must understand the difference between an object and an object-reference. In Java you can never access an object directly. You can access objects only through an object-reference. An object-reference is like (but not the same as) a memory address. All object references have the same size (or maximum possible size) regardless of the size of object they refer to. If your setPrev method was

    void setPrev(Node p) {
       this.prev = p;
    }
    

    that changes the object-reference this.prev to refer to (point to) the same object as the object-reference p. It does not copy the object referred to by p into the this object.