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.

AP Computer Science A illustration with code, binary digits, and programming braces
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

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.

SECTION 2

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.

SECTION 3

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.

Memory Model: Dog spot = new Dog("Buddy", 3);STACK (Local Variables)spot0x7A2FReference variable holdsthe address, not the object(Declared type: Dog)HEAP (Object Storage)Dog Object @ 0x7A2Fname:"Buddy"age:3Methods: bark(), getName(),getAge(), toString()(Instance variables have their own copy)points toInstantiation Steps①JVM allocates heap memory for a new Dog object②Instance variables initialized to defaults (null, 0)③Constructor Dog("Buddy", 3) executes, setting name and age④Reference (0x7A2F) returned and stored in spot on the stack
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.

SECTION 4

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

ClassNamevariableName=newClassName(arguments);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

Dogspot;//Declarationonly—spotisnullspot=newDog("Buddy",3);//Instantiation+assignmentDog 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→0double→0.0boolean→falseObjectreferences→nullint → 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.

SECTION 5

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.

Aliasing vs. Creating a New ObjectScenario A: AliasingScenario B: Separate ObjectsDog a = new Dog("Rex", 5);Dog b = a; // alias!abDog"Rex"age: 5@ 0x3C01Both a and b → same objecta == b evaluates to trueDog c = new Dog("Rex", 5);Dog d = new Dog("Rex", 5);cdDog"Rex", 5 @ 0xA1Dog"Rex", 5 @ 0xB7c and d → different objectsc == d evaluates to falseKey Insight• Assignment (=) between reference variables copies the address, not the object → aliasing.• Each use of new creates a distinct object on the heap, even if the constructor arguments are identical.• The == operator on references compares addresses, not the content of the objects.
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.

Two collaborators adjust one blue articulated model while a second model stands apart.Two variables can provide access to one shared object. Copying a reference creates another access path; it does not duplicate the object.

References d1, d2 and d3 are traced through two distinct Dog objects and a null value.Two new expressions create Fido and Rex. After the assignments, d1 refers to Rex, d3 refers to Fido and d2 is null. Both objects remain reachable; == compares reference identity, while equals depends on the class’s implementation.

SECTION 6

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. 1

    Step 1 — Read the Code

    Consider 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. 2

    Step 2 — Trace Line 1

    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.
    s1 → Student("Alice", 90) at heap address, e.g., 0x100
  3. 3

    Step 3 — Trace Line 2

    Student 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. 4

    Step 4 — Trace the Alias

    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 → 0x100 (same object as s1)
  5. 5

    Step 5 — Trace the Mutation

    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.
    Object at 0x100 now has grade = 95
  6. 6

    Step 6 — Predict the Output

    Line 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

SECTION 7

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

Common instantiation pitfalls on the AP CS A exam

✦

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.

SECTION 8

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.

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

How instantiation concepts extend with inheritance

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.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

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?
  • A. c1 == c3
  • B. c2 == c3
  • C. c1 == c2
  • D. c1 == c2 && c2 == c3
Show answer (C)
C is correct. The assignment c2 = c1 copies the reference, making c1 and c2 point to the same object, so c1 == c2 is true. A is incorrect because c3 was created with a separate new call, so it references a different object even though the constructor argument is the same. B is incorrect for the same reason—c2 aliases c1, not c3. D is incorrect because even though the first part (c1 == c2) is true, the second part (c2 == c3) is false, making the entire && expression false.

Question 2: BASIC CALCULATION

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).
  • A. 2
  • B. 10
  • C. 5
  • D. A NullPointerException is thrown
Show answer (B)
B is correct. Because p2 = p1 creates an alias (both reference the same Point object), calling p2.setX(10) modifies the shared object's x value to 10. Therefore p1.getX() returns 10. A is incorrect because it assumes p1 and p2 are separate objects. C is incorrect because getX() returns x, not y. D is incorrect because both references are properly initialized with new (no null reference exists).

Question 3: INTERMEDIATE

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?
  • A. s1 == s2
  • B. s1 == s3
  • C. s3 == s4
  • D. s2 == s4
Show answer (C)
C is correct. Java maintains a String pool (also called the intern pool) for string literals. When you write "hello" as a literal, the JVM reuses the same String object from the pool. Thus s3 and s4 refer to the same object, making s3 == s4 true. A is incorrect because each new String("hello") forces creation of a distinct object on the heap, bypassing the pool. B is incorrect because s1 (created with new) is a different heap object from the pooled literal referenced by s3. D is incorrect because s2 (created with new) is a different heap object from the pooled literal referenced by s4.

Question 4: APPLIED

4 pts
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.
Show answer
Point-by-point rubric: Point 1 — Array declaration and creation: Creates a BankAccount array of the correct length, e.g., BankAccount[] accounts = new BankAccount[names.length]; Point 2 — Loop structure: Uses a loop that correctly iterates over all valid indices of the arrays (e.g., for loop from 0 to names.length − 1). Point 3 — Conditional constructor selection: Uses an if statement to check deposits[i] > 0 and calls the two-argument constructor new BankAccount(names[i], deposits[i]) in the true branch and the one-argument constructor new BankAccount(names[i]) in the else branch. Point 4 — Returns the array: Returns the populated accounts array. Sample solution: public static BankAccount[] createAccounts(String[] names, double[] deposits) { BankAccount[] accounts = new BankAccount[names.length]; for (int i = 0; i < names.length; i++) { if (deposits[i] > 0) { accounts[i] = new BankAccount(names[i], deposits[i]); } else { accounts[i] = new BankAccount(names[i]); } } return accounts; }

Question 5: CRITICAL THINKING

3 pts
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.
Show answer
Point-by-point rubric: Point 1 (Part a): The student's claim is incorrect. Only two Dog objects were ever created (only two uses of new). After execution: the Fido object is referenced by d3 only (1 reference). The Rex object is referenced by d1 only (1 reference). d2 is null and references nothing. Point 2 (Part b): No object is eligible for garbage collection. The Fido object is still reachable through d3, and the Rex object is still reachable through d1. Setting d2 to null removed one reference to Rex, but d1 was reassigned to point to Rex in the previous line, so Rex still has a live reference. Point 3 (Part c):d1 == d3 evaluates to false. After d3 = d1 (when d1 pointed to Fido), d3 points to Fido. Then d1 = d2 reassigns d1 to point to Rex. Now d1 points to Rex and d3 points to Fido—they reference different objects, so == returns false.

SUMMARY

Lesson Summary

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)