AP Computer Science A

1.13 – Object Creation and Storage (Instantiation)

1. What Does It Mean to Create an Object?

In Java, a class is a blueprint. An object is a real instance created from that blueprint.

We create objects using the new operator, which allocates memory and returns a reference to that object.

2. General Syntax for Object Creation

ClassName variableName = new ClassName(parameters);
    

Examples:

String name = new String("Tiger");
Scanner input = new Scanner(System.in);
Random rand = new Random();
    

Each statement:

3. Object References

A variable that holds an object does not store the object directly. Instead, it stores a reference (a memory address pointing to the object in the heap).

Student s1 = new Student("Aiden", 11);
    

Here:

4. Multiple References to the Same Object

Two variables can point to the same object.

Student a = new Student("Maria", 12);
Student b = a;
    

Both variables:

5. Null References

Declaring a reference variable without creating an object:

Student s;
    

Setting a reference to null:

Student s = null;
    

A null reference points to no object. Calling a method on a null reference:

s.getName();
    

will cause a NullPointerException.

6. Memory and the Heap

When we use new, Java places the object in a memory area called the heap. Reference variables (like s1 or rand) live in stack memory and only hold the address of the object on the heap.

7. Garbage Collection

Java automatically removes objects from memory when no references point to them.

Student s = new Student("Luis", 10);
s = new Student("Emma", 12);
    

The first object (“Luis”) has no references and becomes garbage. Java’s garbage collector will remove it later.

8. Summary