No, it’s not entirely true that primitive data types are always stored on the stack and instances of objects are always stored on the heap. The actual memory allocation depends on where and how the variable is declared. Let’s break it down.
1. Primitive Data Types Storage
Primitive data types (int, double, char, boolean, etc.) are not always stored on the stack. Their location depends on how they are declared.
Case 1: Local Primitives (Stored in Stack)
If a primitive is a local variable inside a method, it will be stored on the stack.
public class Test {
public static void main(String[] args) {
int x = 10; // 'x' is stored in Stack
}
}
✅ x
is stored in the stack because it’s a local variable.
Case 2: Instance Variables (Stored in Heap)
If a primitive is a field of an object, it is stored inside the object on the heap.
class Person {
int age; // Stored in Heap (inside the object)
}
public class Test {
public static void main(String[] args) {
Person p1 = new Person(); // 'p1' is stored in Stack, but the object is in Heap
p1.age = 25; // 'age' is stored in Heap (inside 'p1' object)
}
}
✅ age
is stored inside the Person object, which is in the Heap.
2. Object Instances Storage
Instances of objects are always stored on the heap, but references to them can be on the stack.
class Car {
String model;
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // 'myCar' is stored in Stack, but the object is in Heap
}
}
✅ myCar
(the reference) is stored on the stack, but the Car
object itself is in heap memory.
3. Special Case: Primitive Wrapper Classes
Primitive wrapper classes like Integer, Double, Boolean, etc. are objects, so they are stored in the heap.
Integer num = 100; // num (reference) in Stack, object in Heap
✅ num
(reference) is stored in stack, but 100
(as an Integer
object) is in heap.
Conclusion
Data Type | Stored in Stack? | Stored in Heap? |
---|---|---|
Local primitives (inside a method) | ✅ Yes | ❌ No |
Instance variables (inside an object) | ❌ No | ✅ Yes |
Object references (pointers) | ✅ Yes | ❌ No |
Object instances | ❌ No | ✅ Yes |
Wrapper classes (Integer , Double , etc.) | ❌ No | ✅ Yes |