The new Keyword: Allocating Objects on the Heap
What you'll learn: How the new keyword creates objects in memory and gives you a reference to find them.
The Core Idea
When you work with reference types (like arrays or objects), you need a way to actually create the thing you want to reference. That's where the new keyword comes in. When you use new, Java does two important things:
- Allocates memory on the heap for your object
- Returns a reference (a memory address) pointing to that newly allocated space
Think of it like buying a storage unit. When you rent one, the storage company allocates physical space for you and gives you the unit number. You don't carry the storage unit around—you carry the number that lets you find it. Similarly, new doesn't give you the actual object; it gives you a reference to where the object lives in memory.
How It Works
int[] numbers = new int[5]; // new allocates heap memory for 5 integers
String[] names = new String[3]; // new allocates space for 3 String references
In the first line:
new int[5]asks Java to allocate enough heap memory for 5 integers- Java reserves that space and returns a reference to it
- That reference is stored in the variable
numbers
Without new, you'd only have a reference variable with nowhere to point—like having a storage unit number for a unit that doesn't exist.
Stack vs Heap Reminder
The reference variable (numbers) lives on the stack. The actual array lives on the heap. The new keyword bridges these two worlds by creating the heap object and giving you its address.
Key Takeaway: The new keyword allocates memory on the heap for an object and returns a reference to that memory location, which you store in a variable.