Storage of object references inside a object in Java memory model -


while studying linked list implementation need clarify how reference , object store in stack , heap kind of scenario object self has references,

public class mylinkedlist {      private node head;     private int listcount;      public mylinkedlist() {         head = new node("0");         listcount = 0;     }      public void add(object data) {         node nodetemp = new node(data);         node nodecurr = head;          while (nodecurr.getnext() != null) {             nodecurr = nodecurr.getnext();         }          nodecurr.setnext(nodetemp);         listcount++;      } }  public class linkedlistmain {     public static void main(string[] args) {         mylinkedlist ls = new mylinkedlist();         ls.add("1"); } 

now mylinkedlist object refer "ls" reference in stack , mylinkedlist self in heap. understood.

but mylinkedlist constructor when create new node refer "head" reference "head" reference store? doubt since "node head" inside (belong to) mylinkedlist object, "head" store in stack with "ls" or kind of inside mylinkedlist object?

two important things java need understand:

  1. all java objects allocated in java heap. of them.
  2. in java, variables never objects. never. variable can reference object. (or variable can primitive int, not objects.)

what means main method allocates mylinkedlist object, on java heap, , stores reference object in variable named ls. mylinkedlist object (which doesn't have name) can store reference node object (which stored on java heap) in local field called head.

no other object ever stored "inside" object. references other objects stored inside.

caveat: while answer correct i'm regard how java language works, runtime allowed make various optimizations long can't tell difference. example, "the java heap" not heap in algorithmic sense, , not in same sense "the c++ heap". java jit allowed allocate java objects stack-like structure (the younggen) or current stack (due escape analysis). said, implementation details not relevant when you're learning language.