AP Computer Science A
One-page, printable cheatsheet
Cheatsheet visualization
Table of Contents

💻ap computer science a review

2.2 Creating and Storing Objects (Instantiation)

Verified for the 2025 AP Computer Science A examCitation:

In Java, constructors play a vital role in the object creation process, initializing new objects and establishing their initial state. Understanding how constructors work, how to identify them, and how to use them properly is fundamental to effective object-oriented programming. This guide explores the nature of constructors, their signatures, parameters, and their role in creating objects.

Understanding Constructors

What is a Constructor?

Constructors are special methods that are called when an object is created. They have the same name as the class and are responsible for initializing the object's state.

public class Student {
    private String name;
    private int grade;
    
    // This is a constructor
    public Student(String studentName, int studentGrade) {
        name = studentName;
        grade = studentGrade;
    }
}

Constructor Signatures

A signature consists of the constructor name and the parameter list. The signature uniquely identifies which constructor is being called.

// Constructor with signature: Student(String, int)
public Student(String name, int grade) { ... }

// Different constructor with signature: Student()
public Student() { ... }

Constructor Parameters

Formal Parameters

The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names. These are often referred to as formal parameters.

// name and age are formal parameters
public Person(String name, int age) {
    // Constructor body
}

Actual Parameters

A parameter is a value that is passed into a constructor. These are often referred to as actual parameters or arguments.

// "John" and 25 are actual parameters
Person person = new Person("John", 25);

Parameter Compatibility

The actual parameters passed to a constructor must be compatible with the types identified in the formal parameter list.

public Rectangle(int width, int height) { ... }

// Correct - parameters match expected types

Rectangle rect1 = new Rectangle(5, 10);

// Error - incompatible types

Rectangle rect2 = new Rectangle("five", "ten");

Call by Value

Parameters are passed using call by value. Call by value initializes the formal parameters with copies of the actual parameters.

public class Example {
    public static void main(String[] args) {
        int x = 5;
        Test obj = new Test();
        obj.modify(x); // Pass x by value
        System.out.println(x); // Still prints 5
    }
}

class Test {
    public void modify(int n) {
        n = n * 2; // Changes only the local copy
    }
}

Constructor Overloading

Constructors are said to be overloaded when there are multiple constructors with the same name but a different signature.

public class Book {
    private String title;
    private String author;
    private int pages;
    
    // Constructor 1
    public Book() {
        title = "Unknown";
        author = "Unknown";
        pages = 0;
    }
    
    // Constructor 2
    public Book(String title) {
        this.title = title;
        author = "Unknown";
        pages = 0;
    }
    
    // Constructor 3
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }
}

Creating Objects

The new Keyword

Every object is created using the keyword new followed by a call to one of the class's constructors.

// Create a String object
String message = new String("Hello");

// Create a Scanner object
Scanner input = new Scanner(System.in);

// Create a custom object
Student student = new Student("Alice", 11);

Constructor Invocation

A class contains constructors that are invoked to create objects. They have the same name as the class.

public class Car {
    private String model;
    
    // Constructor name matches class name
    public Car(String model) {
        this.model = model;
    }
}

// Creating a Car object by invoking the constructor
Car myCar = new Car("Tesla");

Using Existing Classes

Existing classes and class libraries can be utilized as appropriate to create objects.

// Using existing Java classes
ArrayList<String> names = new ArrayList<>();
Random generator = new Random();
Date today = new Date();

// Using third-party libraries (example)
// DecimalFormat formatter = new DecimalFormat("#,###.##");

Object Initialization

Parameters allow values to be passed to the constructor to establish the initial state of the object.

public class BankAccount {
    private String accountNumber;
    private double balance;
    
    public BankAccount(String accountNumber, double initialDeposit) {
        this.accountNumber = accountNumber;
        this.balance = initialDeposit;
        // The object's initial state is now established
    }
}

// Initial state set through constructor parameters
BankAccount account = new BankAccount("12345", 1000.00);

Reference Variables and null

Understanding null

The keyword null is a special value used to indicate that a reference is not associated with any object.

// Declaring a reference variable with no object
Student student = null;

// Check for null before using
if (student != null) {
    student.getName(); // Safe to call
} else {
    System.out.println("Student is null!");
}

Reference Variables in Memory

The memory associated with a variable of a reference type holds an object reference value or, if there is no object, null. This value is the memory address of the referenced object.

Student alice;       // Declaration only - contains undefined value

alice = new Student("Alice", 10);  // alice now contains a reference
alice = null;        // alice now contains null
alice = new Student("Alice B.", 11);  // alice now references a different object

Common Errors with null

(NullPointerException: occurs when a program tries to access or use an object that has not been initialized, meaning it is currently set to "null".)

// NullPointerException example
String name = null;
int length = name.length(); // Throws NullPointerException

// Proper handling
if (name != null) {
    int length = name.length(); // Safe
} else {
    System.out.println("Name is null");
}

Remember that constructors are essential for creating objects with the correct initial state. By understanding constructor signatures, parameters, and the object creation process, you can effectively design and use classes in your Java programs.

Key Terms to Review (12)

Class: A class is a blueprint or template for creating objects in object-oriented programming. It defines the properties and behaviors that an object of that class will have.
Constructor Overloading: Constructor overloading is a feature in OOP that allows multiple constructors with different parameter lists within a single class. Each constructor can initialize an object with different sets of values.
IllegalArgumentException: An IllegalArgumentException is an exception that occurs when a method receives an argument that is inappropriate or invalid for its intended purpose. It usually indicates that there was an error in how arguments were passed into a method.
Key Term: Object: An object is an instance of a class that encapsulates data and behavior. It represents a real-world entity or concept in the program.
New Keyword: The new keyword is used in Java to create an instance (object) of a class. It allocates memory for the object and initializes its attributes using the constructor method.
Object-oriented programming (OOP): Object-oriented programming is a programming paradigm that organizes code into objects, which are instances of classes. It emphasizes the use of objects to represent real-world entities and their interactions.
NullPointerException: A NullPointerException occurs when a program tries to access or use an object that has not been initialized, meaning it is currently set to "null".
Parameter List: A parameter list is a set of input parameters/arguments that are passed to a method or constructor when it is called. It specifies the type and order of the values that need to be provided for the method/constructor to execute correctly.
Parameters: Parameters are variables declared in a method or function that receive values when the method is called. They allow data to be passed into a method, enabling it to perform actions or calculations based on those values.
Pass-by-value language: Pass-by-value language refers to programming languages where copies of variable values are passed into functions. Any changes made to these copies do not affect the original variables.
Primitive value: A primitive value is a basic data type in programming that represents simple pieces of information such as numbers or characters.
Reference Type: A reference type is a data type that stores the memory address of an object rather than the actual value. It allows multiple variables to refer to the same object, and changes made to one variable will affect all other variables referencing that object.