Loading
Understanding how the new keyword allocates objects on the heap and binds them to reference variables.
Before object-oriented programming became dominant, software developers organized code around procedures—sequences of instructions that operated on passive data structures. As programs grew in complexity during the 1960s and 1970s, this procedural paradigm struggled to manage the tangled interdependencies between data and the functions that manipulated it. The concept of instantiation—creating a living object from a class blueprint—emerged as a central mechanism in object-oriented programming, enabling developers to encapsulate state and behavior into self-contained entities. This idea changed how we reason about program architecture: rather than thinking in terms of global data flowing through functions, we think of autonomous objects that communicate by sending messages (calling methods) to one another.
new keyword for object instantiation—the first language to treat data and behavior as a single unit.new, and is accessed exclusively through reference variables—the exact model tested on the AP Computer Science A exam.The central question that object instantiation answers is deceptively simple: How does a static class definition become a dynamic, usable entity at runtime? The answer involves memory allocation, constructor invocation, and reference binding—three intertwined steps that you must understand deeply for both the multiple-choice and free-response sections of the AP exam.
Object instantiation in Java rests on a clean separation between the class (the template) and the object (the concrete instance). A class defines the structure—instance variables and methods—but by itself occupies no heap space for those fields. Only when you invoke the new keyword does the Java Virtual Machine allocate memory, initialize the fields, run the constructor, and return a reference to the newly minted object. The following foundational ideas underpin every instantiation you will encounter on the AP exam.
new operator allocates heap memory for the object, initializes instance variables to default values, and then invokes the specified constructor. It returns a reference (memory address) to the newly created object.null.null. Calling a method on a null reference produces a NullPointerException at runtime—one of the most common bugs in Java programs.new is like hiring a contractor to actually build the house on a specific lot (heap memory). The address you write on your mail (the reference variable) tells you where the house is, but the address is not the house itself. Multiple people can have the same address written down, and they all reach the same house.Understanding object instantiation requires a clear mental model of how Java organizes memory. The JVM divides runtime memory into two principal regions relevant to AP CS A: the stack, where local variables and reference variables live, and the heap, where objects created with new reside. The following diagram traces the execution of a single instantiation statement.
spot which holds address 0x7A2F. The heap (right, pink) stores the actual Dog object with its instance variables and methods. The dashed arrow shows the reference relationship.Notice the critical distinction illustrated in the diagram: the variable spot on the stack does not contain the Dog object itself—it contains a reference (conceptually, a memory address) that points to the actual object on the heap. This distinction matters profoundly when you pass objects to methods or assign one reference variable to another: you are copying the address, not the object. Two references can therefore point to the same object, and mutating the object through one reference makes the changes visible through the other.
The general syntax for declaring a reference variable and instantiating an object in Java follows a predictable pattern. Understanding each component of this pattern is essential for reading and writing AP exam code with confidence.
This single line actually performs two distinct operations that can also be written separately. The declaration (ClassName variableName) creates a reference variable on the stack, initially holding null. The instantiation and assignment (= new ClassName(arguments)) creates the object on the heap and stores its address in the reference variable.
A class can define multiple constructors with different parameter lists—this is called constructor overloading. The compiler determines which constructor to call based on the number and types of arguments you pass. For instance, a Dog class might offer a two-argument constructor Dog(String name, int age) and a no-argument constructor Dog() that assigns default values. On the AP exam, you must match the arguments you provide with the constructor signature exactly; a mismatch causes a compile-time error.
One of the most nuanced—and most tested—aspects of object instantiation is what happens when you assign one reference variable to another. This operation copies the reference, not the object, producing what is called an alias. Aliasing means two or more variables refer to the exact same object on the heap. Changes made through one alias are immediately visible through the other because there is only one underlying object.
a and b point to the same Dog object, so a == b is true. Scenario B shows two separate calls to new, creating distinct objects even with identical field values, so c == d is false.This distinction between reference equality (tested with ==) and content equality (tested with the .equals() method) is one of the most commonly tested topics on the AP exam. The == operator compares the memory addresses stored in two reference variables, returning true only if both references point to the very same object. The .equals() method, when properly overridden, compares the actual state (field values) of the objects.
Let us trace through a short program that creates and manipulates objects, predicting the output at each stage. This kind of step-by-step tracing is directly analogous to what you will need to do on multiple-choice questions that present code snippets and ask for printed output.
Student class with a constructor Student(String name, int grade), a method getName() that returns the name, and a method setGrade(int g) that changes the grade.
Student s1 = new Student("Alice", 90);
Student s2 = new Student("Bob", 85);
Student s3 = s1;
s3.setGrade(95);
System.out.println(s1.getName() + " " + s1.getGrade());
System.out.println(s2.getName() + " " + s2.getGrade());
System.out.println(s1 == s3);Student s1 = new Student("Alice", 90); — The JVM allocates a new Student object on the heap with name = "Alice" and grade = 90. The reference is stored in s1.Student s2 = new Student("Bob", 85); — A second, completely separate Student object is created on the heap.Student s3 = s1; — No new keyword means no new object is created. The address stored in s1 (0x100) is copied into s3. Both references now point to the same Student object.s3.setGrade(95); — This calls setGrade on the object at 0x100, changing its grade from 90 to 95. Because s1 and s3 point to the same object, accessing s1.getGrade() will also return 95.Alice 95 (not 90, because s3 mutated the shared object). Line 2 prints: Bob 85 (s2 references a completely separate object, unaffected). Line 3 prints: true because s1 and s3 hold the same memory address.Alice 95
Bob 85
trueAP exam questions are carefully designed to exploit common misconceptions about object creation. The table below summarizes the most frequent mistakes students make and contrasts them with the correct understanding.
| Common Mistake | Why It's Wrong | Correct Understanding |
|---|---|---|
Using == to compare object contents | == compares references (memory addresses), not the values of instance variables. | Use .equals() for content comparison. For Strings, .equals() checks character sequences. |
Forgetting that = copies the reference, not the object | Students expect b = a to create a separate copy. It doesn't—it creates an alias. | After b = a, both variables share one object. Mutating through b affects a. |
Calling a method on a null reference | Declaring Dog d; without instantiation leaves d as null. Calling d.bark() throws a NullPointerException. | Always ensure a reference has been assigned to a new object (or a non-null value) before calling methods on it. |
| Mismatched constructor arguments | Passing the wrong number or types of arguments does not cause a runtime error—it fails to compile. | Match argument count and types to a declared constructor signature. The compiler selects the constructor via overload resolution. |
| Thinking primitives are objects | int, double, boolean are not objects. They are stored directly in the variable, not by reference. | Primitive variables hold values directly. Object variables hold references. Use wrapper classes (Integer, Double) when you need an object. |
b = a), think of handing someone a copy of a house key, not building them a new house. Both keys open the same front door, so any changes made inside by one person are visible to the other. A new house is only built when you see the new keyword.Object instantiation becomes considerably more nuanced once you encounter inheritance and polymorphism later in the AP curriculum. Java allows you to declare a variable of a superclass type and assign it an instance of a subclass. For example, Animal pet = new Dog("Buddy", 3); is valid if Dog extends Animal. The declared type (Animal) determines which methods can be called at compile time, while the actual type (Dog) determines which version of an overridden method runs at runtime. This principle, called polymorphism, builds directly on the reference model you learned in this lesson.
| Concept | Basic Instantiation (This Lesson) | Advanced (Inheritance Unit) |
|---|---|---|
| Declaration type | Same as the class being instantiated | Can be a superclass or interface type |
| Constructor chain | Single constructor executes | Superclass constructors called first via super() |
| Method binding | Declared type = actual type, so binding is straightforward | Dynamic dispatch: JVM calls the overridden method in the actual object's class |
| Casting | Not needed | Downcasting may be required to access subclass-specific methods |
Even though these advanced topics appear later, the reference model you have built in this lesson is the same: the new keyword always creates an object on the heap, and a reference variable always stores an address. What changes is only which methods the compiler lets you call (determined by the declared type) versus which method bodies actually execute (determined by the actual object type). Mastering basic instantiation now will make inheritance and polymorphism feel like natural extensions rather than entirely new ideas.
Cat c1 = new Cat("Whiskers");
Cat c2 = c1;
Cat c3 = new Cat("Whiskers");
Which of the following expressions evaluates to true?Point p1 = new Point(2, 5);
Point p2 = p1;
p2.setX(10);
System.out.println(p1.getX());
What is printed? Assume Point has a constructor Point(int x, int y) and methods getX() and setX(int x).String s1 = new String("hello");
String s2 = new String("hello");
String s3 = "hello";
String s4 = "hello";
Which of the following evaluates to true?BankAccount with instance variables String owner and double balance. The class has the following constructors:
public BankAccount(String owner, double balance)
public BankAccount(String owner)
The second constructor sets the balance to 0.0.
Write a method public static BankAccount[] createAccounts(String[] names, double[] deposits) that creates and returns an array of BankAccount objects. For each index i, if deposits[i] > 0, use the two-argument constructor; otherwise, use the one-argument constructor. You may assume both arrays have the same length.Dog objects in memory."
Dog d1 = new Dog("Fido");
Dog d2 = new Dog("Rex");
Dog d3 = d1;
d1 = d2;
d2 = null;
(a) Explain whether the student's claim is correct. State how many Dog objects exist in heap memory and how many reference variables point to each.
(b) Identify which object, if any, is eligible for garbage collection after this code executes, and explain why.
(c) State the result of evaluating d1 == d3 after this code and explain your reasoning.In Java, object instantiation is the process of creating a concrete instance of a class using the new keyword. This operation allocates memory on the heap, initializes instance variables to default values, executes the matching constructor, and returns a reference to the newly created object. A reference variable stores the memory address of the object, not the object itself—this means assigning one reference to another creates an alias, not a copy.
Remember that the == operator compares reference addresses (not object contents), while .equals() compares state. A reference that has been declared but not assigned to a new object holds null, and calling a method on it produces a NullPointerException. These concepts form the foundation for every subsequent AP CS A topic—from arrays of objects to inheritance and polymorphism.
Keep learning with more lessons from the same subject.