Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Layman Explanation

Imagine a school with 50 students. Every student has their own name and roll number. But the school name is SAME for all. Why store "DPS School" 50 times? Store it ONCE and let all students share it. That's a static variable.

What is a Static Variable?

A static variable belongs to the CLASS — not to any individual object. All objects share the SAME single copy.
java
QUBITS OF DPK
1class Student {
2    String name;              // instance — each object gets own copy
3    int rollNumber;           // instance — each object gets own copy
4    static String schoolName = "DPS School";  // ONE copy for all
5    static int totalStudents = 0;              // shared counter
6}

Memory Model

javascript
QUBITS OF DPK
1Heap:
2Object 1 (Deepak):          Object 2 (Arjun):
3┌───────────────────┐       ┌───────────────────┐
4│ name = "Deepak"   │       │ name = "Arjun"5│ roll = 101        │       │ roll = 1026└───────────────────┘       └───────────────────┘
7
8Method Area (class level):
9┌──────────────────────────────┐
10│ schoolName = "DPS School" │ ◄── shared by ALL
11└──────────────────────────────┘

Full Example

java
QUBITS OF DPK
1class Student {
2    String name;
3    static int totalStudents = 0;
4
5    Student(String name) {
6        this.name = name;
7        totalStudents++;   // increments shared counter
8    }
9}
10
11Student s1 = new Student("Deepak");
12Student s2 = new Student("Arjun");
13Student s3 = new Student("Priya");
14
15System.out.println(Student.totalStudents);  // 3

Accessing Static Variable

java
QUBITS OF DPK
1// Via class name — RECOMMENDED ✅
2Student.schoolName = "New School";
3
4// Via object — works but misleading ⚠️
5s1.schoolName;   // looks like instance variable!

Production Use Cases

java
QUBITS OF DPK
1// 1. Counter
2static int totalRequests = 0;
3
4// 2. Constants
5static final double PI = 3.14159;
6static final String GATEWAY_URL = "https://api.stripe.com/v1";
7
8// 3. Configuration
9static String appName = "PaymentService";
10static int maxRetries = 3;
11
12// 4. Singleton Pattern
13private static PaymentService instance;

️ All Traps

java
QUBITS OF DPK
1// Trap 1 — Changing static affects ALL objects
2Student.schoolName = "New School";
3// ALL student objects now see "New School"
4
5// Trap 2 — Cannot use 'this' with static
6static void show() {
7    this.schoolName;   // ❌ no 'this' in static context
8}
9
10// Trap 3 — Static lives until program ends
11// Not garbage collected as long as class is loaded

Interview Answer (SDE-2)

"A static variable belongs to the class rather than any object — stored in Method Area, shared by all instances, initialized when class loads. Instance variables have separate copies per object; static variables have one copy for the entire class. Access via class name to make shared nature explicit. Used for counters, constants, configuration values, and Singleton patterns. In a payment service, gateway URL should be static final — same for every transaction, no reason to create per object."

Interview Questions & MAANG-Level Answers

Q1. What is a static variable and where is it stored?
A static variable belongs to the class itself, not to any instance. It is stored in the Method Area (part of JVM memory), initialized when the class is loaded, and lives until the program ends. All instances share the same copy. Example: static int totalUsers = 0 — incremented in constructor to count all objects ever created.
Q2. What is the difference between static and instance variables?
Instance variables: each object gets its own independent copy, stored inside the object in heap, initialized per object creation, dies when object is garbage collected. Static variables: ONE copy shared by all objects, stored in Method Area, initialized once when class loads, lives for the entire program duration. Example: name (instance — each user has their own name), totalUsers (static — one count for all users).
Q3. Can you change a static variable? What happens to other objects?
Yes, static variables can be changed (unless final). When changed, ALL objects immediately see the new value since they all share the same copy. Student.schoolName = "New School" — every Student object now sees "New School" when accessing schoolName. This shared mutability can cause bugs in multi-threaded code — use synchronized or AtomicInteger for thread-safe static counters.
Q4. What is static final and when do you use it?
static final is a class-level constant — one copy, never changes. Best practice for magic numbers and configuration values:
java
QUBITS OF DPK
1static final double PI = 3.14159;
2static final String GATEWAY_URL = "https://api.stripe.com/v1";
3static final int MAX_RETRY_COUNT = 3;
By convention, use UPPER_SNAKE_CASE. Evaluated at compile time if primitive — the compiler may inline the value directly.
Q5. Why should you access static variables via class name?
Accessibility and clarity. Student.schoolName makes it immediately obvious that schoolName is a class-level (shared) variable. s1.schoolName looks like an instance variable — misleading to readers and maintainers. Most IDEs and code linters warn when accessing static members via instance reference. Always prefer ClassName.staticMember for readability and correctness.