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

🧠 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!




Source link

Leave a Reply

Your email address will not be published. Required fields are marked *