AP COMPUTER SCIENCE A • USING OBJECTS AND METHODS

Object Creation and Storage (Instantiation)

Understanding how the new keyword allocates objects on the heap and binds them to reference variables.

Historical Context & Motivation

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.

1967
Simula Introduces Classes and Objects
Ole-Johan Dahl and Kristen Nygaard create Simula in Norway, introducing classes, objects, and the new keyword for object instantiation—the first language to treat data and behavior as a single unit.
1972
Smalltalk Refines Message-Passing
Alan Kay's Smalltalk at Xerox PARC made "everything is an object" a first-class design principle, deepening the notion that objects are created at runtime and interact solely through message sends.
1983
C++ Brings OOP to Systems Programming
Bjarne Stroustrup adds classes and constructor-based instantiation to C, producing C++ and proving that object creation can coexist with low-level memory management.
1995
Java Standardizes the Reference Model
James Gosling and Sun Microsystems release Java, which mandates that every object lives on the heap, is created with new, and is accessed exclusively through reference variables—the exact model tested on the AP Computer Science A exam.
2003
AP CS A Adopts Java
The College Board transitions the AP Computer Science A exam from C++ to Java, making object instantiation and reference semantics a foundational topic for hundreds of thousands of students annually.

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.

Core Principles & Definitions

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.

1

Class vs. Object

A class is a blueprint that specifies instance variables and methods. An object is a specific instance of that class, created at runtime, with its own copy of instance variable values stored on the heap.
2

The new Keyword

The 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.
3

Reference Variable

A reference variable does not hold the object itself—it holds the address of the object in heap memory. Multiple reference variables can point to the same object, and a reference can be reassigned or set to null.
4

Constructors

A constructor is a special method with the same name as the class and no return type. It initializes the object's state. If no constructor is written, Java provides a default no-argument constructor that sets fields to default values (0, false, or null).
5

Null References

A reference variable declared but not yet assigned to an object holds null. Calling a method on a null reference produces a NullPointerException at runtime—one of the most common bugs in Java programs.
KEY TAKEAWAY
Think of a class as an architectural blueprint for a house: it describes how many rooms there are, their dimensions, and where the doors go, but you cannot live in a blueprint. Calling 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.

Visual Explanation: Memory Model

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.

The stack (left, cyan) stores the reference variable 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.

How Instantiation Works: Syntax & Semantics

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.

INSTANTIATION SYNTAX
ClassName variableName = new ClassName(arguments);
ClassName (left of =) is the declared type of the reference variable. variableName is the identifier for the reference. new ClassName(arguments) allocates heap memory, invokes the matching constructor with the given arguments, and returns a reference to the new object.

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.

SPLIT DECLARATION AND INSTANTIATION
Dog spot; // Declaration only — spot is null spot = new Dog("Buddy", 3); // Instantiation + assignment
Splitting these steps is legal and common in conditional logic where you may want to instantiate different objects based on a condition.

Constructor Overloading

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.

DEFAULT INITIAL VALUES
int → 0 double → 0.0 boolean → false Object references → null
When an object is created, its instance variables are automatically set to these defaults before the constructor body runs. The constructor then assigns meaningful values.

Reference Semantics & Aliasing

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.

Scenario A shows aliasing: both 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.

Worked Example: Tracing Object Creation

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.

Tracing Instantiation, Aliasing, and Method Calls
1
Step 1 — Read the CodeConsider the following code. Assume a 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);
2
Step 2 — Trace Line 1Student 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.
s1 → Student("Alice", 90) at heap address, e.g., 0x100
3
Step 3 — Trace Line 2Student s2 = new Student("Bob", 85); — A second, completely separate Student object is created on the heap.
s2 → Student("Bob", 85) at heap address, e.g., 0x200
4
Step 4 — Trace the AliasStudent 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 → 0x100 (same object as s1)
5
Step 5 — Trace the Mutations3.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.
Object at 0x100 now has grade = 95
6
Step 6 — Predict the OutputLine 1 prints: 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 true

Common Pitfalls & Comparisons

AP 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 instantiation pitfalls on the AP CS A exam
Common MistakeWhy It's WrongCorrect 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 objectStudents 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 referenceDeclaring 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 argumentsPassing 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 objectsint, 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.
KEY TAKEAWAY
When you see an assignment between two object variables (like 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.

Connection to Inheritance & Polymorphism

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.

How instantiation concepts extend with inheritance
ConceptBasic Instantiation (This Lesson)Advanced (Inheritance Unit)
Declaration typeSame as the class being instantiatedCan be a superclass or interface type
Constructor chainSingle constructor executesSuperclass constructors called first via super()
Method bindingDeclared type = actual type, so binding is straightforwardDynamic dispatch: JVM calls the overridden method in the actual object's class
CastingNot neededDowncasting 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.

Practice Problems

1
Consider the following code segment: Cat c1 = new Cat("Whiskers"); Cat c2 = c1; Cat c3 = new Cat("Whiskers"); Which of the following expressions evaluates to true?
2
Consider the following code: 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).
3
Consider the following code segment: String s1 = new String("hello"); String s2 = new String("hello"); String s3 = "hello"; String s4 = "hello"; Which of the following evaluates to true?
PROBLEM 4APPLIED
A programmer is writing a class 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.
PROBLEM 5CRITICAL THINKING
A student claims: "After executing the following code, there are three 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.

Lesson Summary

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.

Varsity Tutors • AP Computer Science A • Object Creation and Storage (Instantiation)