Topic 1.13 — Object Creation and Storage (Instantiation)
Goal: create objects using new, store object references in variables, and understand that variables can refer to different objects (or none).
The big idea
Instantiation means creating a new object. In Java, you usually create objects with the keyword new.
The variable doesn’t store the whole object—it stores a reference to it.
Pattern: ClassName var = new ClassName(...);
Two-step thinking
- Create an object (with
new). - Store a reference to that object in a variable.
This is why we call these “reference variables” for objects.
Common syntax
// Declare a reference variable (doesn't create an object yet)
String s;
// Create + store in one line
s = new String("hi");
// Often shown as:
String t = new String("hello");
With String, you’ll also see literals like "hello" (that’s a special Java convenience).
Reference variables can change what they refer to
A reference variable can be reassigned to refer to a different object.
String s = new String("A");
s = new String("B"); // now s refers to a different object
null (no object)
A reference variable can hold null, which means it isn’t referring to any object.
String s = null; // s refers to nothing
If you try to call a method on null, it causes an error (you’ll see this later).
Primitive vs. reference storage
Primitive
int x = 7; // x stores 7 directly
Reference
String s = new String("hi");
// s stores a reference to the object
Exam mindset
newcreates a new object.- Object variables store references (not the whole object).
- Reassigning a reference variable changes what it points to.
nullmeans “no object.”
Quick self-check
- What does “instantiate” mean?
- What does
newdo? - Does a reference variable store the object itself or a reference to it?
- What does
nullmean? - Can a reference variable be reassigned to refer to a different object?