Cosmic Module
J
Qubits of DPK
March 14, 2026
Core Java
Layman Explanation
A variable is a named box in memory where you store a value. The box has a label (name), a type (what it can hold), and a value inside.
Types of Variables
javascript
QUBITS OF DPK
Local Variable
java
QUBITS OF DPK
Instance Variable
java
QUBITS OF DPK
Static Variable
java
QUBITS OF DPK
Variable Declaration Rules
- Must start with letter, $, or _ — NOT a digit
- Case sensitive (age ≠ Age)
- Cannot use reserved keywords (int, class, static)
- camelCase convention: studentName, totalMarks
Default Values
️ Local variables have NO default — must initialize before use.
️ Common Traps
java
QUBITS OF DPK
Interview Answer
"Java has three variable types. Local variables live inside methods, have no default value, and must be initialized before use. Instance variables belong to objects, stored in heap, and have default values. Static variables belong to the class, stored in Method Area, shared by all objects. Variable naming follows camelCase convention and cannot start with a digit or use reserved keywords."
Interview Questions & MAANG-Level Answers
Q1. What is the difference between local, instance, and static variables?
Local variables are declared inside a method, live on the stack, have no default value, and die when the method returns. Instance variables are declared inside a class but outside methods, live in heap (inside the object), have default values (0, false, null), and each object gets its own copy. Static variables are declared with static, live in Method Area, have one shared copy across all instances, and are initialized when the class loads.
java
QUBITS OF DPK
Q2. What is the default value of an int instance variable?
0. All numeric instance variables default to 0, boolean defaults to false, char to 'u0000', and all reference types (String, objects, arrays) to null. Note: local variables have NO default value — using an uninitialized local variable is a compile error.
Q3. Why do local variables not have default values?
By design — it forces developers to explicitly initialize variables, preventing bugs from accidentally using garbage/unintended values. Instance variables are initialized by the JVM when an object is created, but local variables are the developer's responsibility. The compiler enforces this by throwing a compile error if you try to read an uninitialized local variable.
Q4. Where are instance variables stored in memory?
Instance variables are stored in the Heap memory, inside the object. When new Car() is called, a Car object is created in heap with its instance fields (brand, speed, color). The reference variable (e.g., Car myCar) lives in the Stack but points to the heap object. This is why instance variables survive method calls — they live as long as the object lives in heap.