DEV Community

Vigneshwaralingam
Vigneshwaralingam

Posted on

๐Ÿง  How a Simple Java Question Taught Me About Static vs Instance Variables : Triggered Questions 2

Triggered Questions 2


๐Ÿš€ The Question That Triggered It All

During my Java practice, I came across this code:

public class Check {
    static int a = 10;
    int b = 20;

    public static void main(String[] args) {
        Check obj1 = new Check();
        Check obj2 = new Check();
        obj1.b = 30;
        obj2.a = 40;
        System.out.println(obj1.a + " " + obj2.b);
    }
}
Enter fullscreen mode Exit fullscreen mode

At first glance, I thought the output would be:

10 30
Enter fullscreen mode Exit fullscreen mode

But the actual output was:

40 20
Enter fullscreen mode Exit fullscreen mode

๐Ÿ˜ฎ Waitโ€ฆ What?! We just changed obj1.b = 30;, then why did it print 20?

This made me stop, dig deep, and finally understand how Java handles memory for static and non-static variables.


๐Ÿงฉ Whatโ€™s Happening Here?

Letโ€™s break it down:

โœ… static int a = 10;

  • This is a class-level variable.
  • Stored in the Method Area (shared memory).
  • Shared across all objects of the class.

โœ… int b = 20;

  • This is an instance variable.
  • Stored in heap memory, separately for each object.
  • Each object gets its own copy of b.

๐Ÿง  Visual Representation (with Diagram)

Image description

Explanation of Diagram:

  • Method Area (top) holds the static variable a.
  • Heap Memory (bottom) contains obj1 and obj2, each with its own b.
  • When obj1.b = 30;, only obj1โ€™s b is affected.
  • When obj2.a = 40;, it updates the shared a, so obj1.a also becomes 40.
  • obj2.b was never changed, so it remains 20.

โœ… Step-by-Step Execution:

  1. a is set to 10 โ†’ lives in Method Area.
  2. obj1 and obj2 are created โ†’ each has their own copy of b = 20.
  3. obj1.b = 30; โ†’ changes only obj1โ€™s b.
  4. obj2.a = 40; โ†’ changes shared a.
  5. Output:
System.out.println(obj1.a + " " + obj2.b);
Enter fullscreen mode Exit fullscreen mode
  • obj1.a โ†’ 40 (shared)
  • obj2.b โ†’ 20 (not changed)

๐Ÿง  Lesson Learned:

Static = shared across objects

Instance = unique to each object

This lesson not only helped me crack this question but also made Javaโ€™s memory model crystal clear.

THANK YOU !

I was confused about memory areas, but now everything is clear. Big thanks to Vijay sir and Vassu bro!


Top comments (0)