Intro
If you want to fully understand Java classes, objects, and linked list references, this blog is for you.
I used to be confused about when to use new
and how references work. Let’s clear it using the box analogy.
The new
keyword
Node n = new Node(10);
Right side (
new Node(10)
) → creates a new box (object) in memory withdata=10
andnext=null
Left side (
n
) → a reference variable storing the box’s address
Analogy:
n
holds the address of a box with 10
inside.
[ data=10 | next=null ] <-- box
^
|
n
Reference without new
Node temp = head;
No new box is created.
temp
just copies the address thathead
has.Both
head
andtemp
point to the same object.
[ data=5 | next=null ] <-- box
^ ^
| |
head temp
Linked List Example
Node head = new Node(5); // new box1
Node temp = head; // temp points to box1
temp.data = 20; // update box1's data
temp.next = new Node(30); // create new box2 and link it
Memory:
[ data=20 | next--> ] <-- box1
^ ^
| |
head temp
\
[ data=30 | next=null ] <-- box2
Linked List:
head → 20 → 30 → null
Rule of Thumb
Use
new
→ When you want a new object/boxDo not use
new
→ When you want to point to an existing object/box
Tricky Example
Node temp = head;
temp = new Node(50);
temp
now points to a new boxhead
still points to the old box
Conclusion
new
= create new boxNo
new
= copy existing box’s addressLinked list traversal uses references, insertion uses new
TL;DR
Understanding Java references and new
keyword is just about knowing the difference between a box’s content and its address.
new
= create fresh boxReference = point to existing box
Top comments (1)