Java variables and memory

πŸ“¦ 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
  • 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:

VariableValue
num5
myDogπŸ‘‰ (points to Dog in Heap)

Heap:

ObjectDetails
DogDog 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?

  1. int is a primitive type (like intbooleancharfloat, etc.)
  2. Primitive types in Java are stored directly inside the Stack.
  3. So age holds 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";

  • String is a class (not a primitive type) β€” it’s an object!
  • Java objects are always created/stored in the Heap.
  • In the Stack, name only 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:

TypeWhere?Why?
Primitive (intchar, etc.)Stack πŸ“„Stored directly, tiny and fast
Objects (StringDogCar, 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