Question: while studying a linked list implementation i need a clarify how the reference and object store in stack and heap for this kind of scenario where object it 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 is refer by "ls" reference which is in stack and the MyLinkedList it self is in heap. That i understood. 

But then from the MyLinkedList constructor when we create new Node which refer by "head" reference where does that "head" reference store? My doubt is since "Node head" is inside (belong to) MyLinkedList object, does "head" store in stack **with "ls"** **or** is it kind of **inside MyLinkedList object**?

Answer: 
Two important things about Java you need to understand:

1. **All** Java *objects* are allocated in the Java heap. All of them.
2. In Java, *variables* are **never** objects. Never. But a variable can be a *reference* to an object. (Or a variable can be a primitive like `int`, but those are also not objects.)

What this means is that your `main` method allocates a `MyLinkedList` object, on the Java heap, and stores a **reference** to that object in a variable named `ls`. That `MyLinkedList` object (which itself doesn't have a name) can store a **reference** to a `Node` object (which will also be stored on the Java heap) in a local field called `head`.

No other object is ever stored "inside" any object. Only *references* to other objects are stored inside.

Caveat: While this answer is correct I'm regard to how the Java **language** works, the runtime is allowed to make various optimizations as long as you can't tell the difference. For example, "the Java heap" is not a heap in the algorithmic sense, and often not even in the same sense as "the C++ heap". The Java JIT is allowed to allocate Java objects from a stack-like structure (the younggen) or even from the current stack (due to escape analysis). That said, those implementation details are not relevant when you're just learning the language.
The "MyLinkedList" object allocated in main() is reference by "ls".
"ls" is on the stack - a local variable of main.
The members of this instance of "MyListedList" are on the heap.
In add(), nodeTemp and nodeCurr are stack variables which are references to nodes. The nodes themselves are on the heap.
"head" is a class member variable, and is on the heap, along with listcount.

In Java, (non-static) class members must always be on the heap.