DEV Community

Abhinav Prakash
Abhinav Prakash

Posted on

Java References Made Easy: Explore the Box Analogy

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);
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Reference without new

Node temp = head;
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Memory:

[ data=20 | next--> ]  <-- box1
       ^       ^
       |       |
      head    temp
                 \
                  [ data=30 | next=null ]  <-- box2
Enter fullscreen mode Exit fullscreen mode

Linked List:

head → 20 → 30 → null
Enter fullscreen mode Exit fullscreen mode

image explaining references through box analogy

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);
Enter fullscreen mode Exit fullscreen mode
  • 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

Top comments (1)