Skip to main content

Command Palette

Search for a command to run...

Java References Made Easy: Explore the Box Analogy

Updated
2 min read
Java References Made Easy: Explore the Box Analogy
A

Hi 👋 I’m Abhinav Prakash - a full-stack dev who loves building with Node.js, React, Next, Astro, MongoDB & Cloud. I share my blogs, learnings, side-projects, and dev journey here 🚀

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 with data=10 and next=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 that head has.

  • Both head and temp 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/box

  • Do 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 box

  • head still points to the old box


Conclusion

  1. new = create new box

  2. No new = copy existing box’s address

  3. Linked 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 box

  • Reference = point to existing box


More from this blog

A

Abhinav Prakash | Blogs

6 posts

I write about programming, AI, open-source tools, and my developer journey.
From building side projects to solving real-world dev problems