1

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
jack.math
  • 29
  • 7
  • 1
    your object have a defined size in this case : 2 pointer . Java field or variable are always references your size here is 2 x (32 or 64 bit) (depending of wich jvm you use). in C : struct s { s* n1; s* n2; }; – Arnault Le Prévost-Corvellec Nov 08 '18 at 07:43
  • you mean the for every pointer (reference) it takes a memory in the heap that is null then we allocate the prev node it changes the reference in the heap and points it to the new Node? – jack.math Nov 08 '18 at 07:47
  • Your objects will not be index based, they will just store the references to the related objects – Brad Nov 08 '18 at 07:50
  • 1
    The objects do not grow in size. They will just point (via `prev` and `next`) to other additional objects. So you will have more objects, not bigger ones. – Thilo Nov 08 '18 at 07:56
  • All Java objects are fixed-size. They cannot grow in size. Now, an object can reference other objects, and the *number* of referenced objects can change, so the total size of an object and it's referenced objects can change, but none of the individual objects can grow in size. – Andreas Nov 08 '18 at 07:57

2 Answers2

1

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.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
0

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.
Tran Ho
  • 1,442
  • 9
  • 15