Course contentsShow
← Java
Lesson 295 of 2,8707. Reference Types and Object FundamentalsFree lesson

Object Allocation with new

How the new keyword triggers memory allocation on the heap and returns a reference to that memory.

Object Allocation with new

What you'll learn: How the new keyword triggers memory allocation on the heap and returns a reference to that memory.


When you use the new keyword in Java, you're asking the Java runtime to perform a specific sequence of actions: allocate memory on the heap for a new object, initialize that memory, and hand you back a reference (memory address) pointing to it.

How new Works

Think of new as placing an order at a factory. You say "I need a new String object" or "I need a new int[] array," and the factory (Java runtime) does three things:

  1. Allocates space on the heap – reserves enough memory to hold all the data that type of object needs
  2. Initializes the memory – sets default values (like 0 for numbers, null for references)
  3. Returns a reference – gives you the "address" where that object now lives

The Connection Between new and References

Every time you write new, you're creating something on the heap. The value you get back is not the object itself—it's a reference pointing to where the object lives in memory.

String s = new String("hello");  // new allocates memory, returns reference
int[] arr = new int[5];           // new allocates array memory, returns reference

Without new, you can't create objects (except for string literals and a few special cases). You can only declare reference variables, but they'll point to null until new gives them something to point to.

Why This Matters

Understanding new clarifies why objects behave differently from primitives. Primitives live directly in their variables; objects live on the heap, and variables hold directions to them. The new keyword is the gatekeeper—it's the only way to request that heap allocation.

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 reference variable.