π¦ All About Java Memory
Hello! I’m Java’s Memory Space! π
I’m here to store everything you create: variables, objects, methods… all of it!
But guess what?
I have TWO special zones inside me:
π Stack Memory
- Quick and small storage.
- Used for:
- Local variables
- Method calls
- References to objects
- Super fast, but gets cleared when the method ends!
π§ Think of it like your desk β only the stuff you’re actively working on.
π¦ Heap Memory
- Big, long-term storage.
- Used for:
- Objects (
new Dog(),new Car()) - Class instances
- Objects (
- Slower, but data stays until you don’t need it anymore!
π‘ Think of it like your closet β you store things youβll use later.
β¨ Fun Code Example:
public class MemoryFun {
public static void main(String[] args) {
int num = 5;
Dog myDog = new Dog();
}
}
π§ Memory Map:
Stack:
| Variable | Value |
|---|---|
| num | 5 |
| myDog | π (points to Dog in Heap) |
Heap:
| Object | Details |
|---|---|
| Dog | Dog object created by new Dog() |
1οΈβ£ Java Variables β What Are They?
π§ Think of variables as little labeled boxes.
int age = 25;
String name = "Charlie";
[STACK] π
-------------
| age = 25 |
| name (ref) | ---> [HEAP] π¦
-------------
| "Charlie" |
-------------
π Variables = Labels
π§Ί Objects/Strings = Things Stored
π Why 25 is in Stack, but "Charlie" is in Heap?
intis a primitive type (likeint,boolean,char,float, etc.)- Primitive types in Java are stored directly inside the Stack.
- So
ageholds the actual value 25 right there in the Stack.
1. int age = 25;
β
No pointer, no object β just the number 25!
2. String name = "Charlie";
Stringis a class (not a primitive type) β it’s an object!- Java objects are always created/stored in the Heap.
- In the Stack,
nameonly stores a reference (a tiny pointer π) to the"Charlie"String object sitting in the Heap.
β
Stack holds a link β Heap holds the actual data "Charlie".
π§ So in short:
| Type | Where? | Why? |
|---|---|---|
Primitive (int, char, etc.) | Stack π | Stored directly, tiny and fast |
Objects (String, Dog, Car, etc.) | Heap π¦ | Bigger, needs long-term space |
β‘ Quick Extra Tip:
Even though "Charlie" is in Heap, if you wrote:
String greeting = "Hello";
Java might optimize it and store it in a special part of Heap called the String Pool to save memory β but still, it’s Heap, not Stack.
π§ Simple Rule:
If itβs a primitive β Stack
If itβs an object β Heap