AP CSA Unit 1 Study Notes: Using Objects and Methods (Objects and Methods)
Objects: Instances of Classes
In Java, an object is a single, usable “thing” your program can work with—something you can ask questions (get information) and tell to do actions. A class is the blueprint or definition that describes what kinds of objects can exist and what they can do. When you create an object from a class, that object is an instance of the class.
A helpful analogy is a cookie cutter (class) and cookies (objects). The cutter defines the shape and rules; each cookie is a separate, real item you can hold, decorate, or eat. Two cookies made from the same cutter are similar, but they are still two distinct cookies.
What a class provides (at this stage)
In Unit 1, you focus less on writing your own classes and more on using existing classes (including ones you may write later). Conceptually, a class provides:
- Constructors: special “setup” code used to create new objects.
- Methods: actions you can ask an object to perform.
- (Often) data/fields: information stored inside each object (you’ll dig deeper into fields later).
When you have an object, you interact with it primarily by calling its methods. This is the central idea of “using objects and methods”: you don’t manually manipulate the object’s internal details; you use the public methods the class provides.
Why objects matter in AP CSA
Objects let you model complex behavior with simpler code. Instead of reinventing features from scratch, you rely on well-tested classes. In AP CSA Unit 1, you’ll frequently use library classes such as String, Math, and sometimes Scanner (depending on teacher choice), and you’ll practice reasoning about what method calls do.
Objects also set you up for later units:
- You’ll learn to write your own classes with fields and methods.
- You’ll build programs where many objects collaborate.
- You’ll trace code that creates objects, changes their state, and uses returned values.
The “dot” operator (member access)
In Java, you use the dot operator (.) to access an object’s methods:
objectReference.methodName(...);
The dot is read like: “ask this object to do this method.” The method you can call depends on the type of the reference (the class).
For example, if a variable has type String, you can call String methods like length() or substring(...). If it has type Random, you can call nextInt(...).
Identity vs. equality (a common early confusion)
Even early on, it helps to separate two ideas:
- Identity: “Are these two references pointing to the exact same object in memory?”
- Equality: “Do these two objects represent the same value/content?”
For String, you typically check content equality using .equals(...), not ==. The == operator compares identity for objects (whether the references are the same), not content.
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // usually false (different objects)
System.out.println(a.equals(b)); // true (same text)
This distinction shows up often in AP-style multiple choice questions.
Example: seeing “instance of a class” in action
String name = "Ava"; // a String object (string literal creates a String)
int n = name.length(); // calls a method on that String object
System.out.println(n); // prints 3
Even though "Ava" looks simple, it’s still an object—an instance of String.
Exam Focus
- Typical question patterns:
- Identify what class an object belongs to and which methods can be called using dot notation.
- Predict the result of calling common methods (especially
Stringmethods likelength,substring,indexOf). - Distinguish between
==and.equals(...)for objects likeString.
- Common mistakes:
- Using
==to compare the contents of twoStringobjects instead of.equals(...). - Assuming an object “is the class” (a class is a blueprint; an object is one instance).
- Forgetting that string literals (like
"hi") still produceStringobjects.
- Using
Creating and Storing Objects
To use an object, you usually need (1) a reference variable to store it and (2) a way to create it. In Java, objects are created with the keyword new followed by a constructor call.
A reference variable doesn’t store the whole object directly; it stores a reference (think: a “handle” or “pointer-like address”) that tells Java where the object is. This matters because:
- Two variables can refer to the same object.
- Assigning one reference variable to another does not “copy the object”; it makes both refer to the same object.
Declaring, instantiating, and initializing
You’ll often see these steps combined, but it’s useful to understand them separately:
- Declare a reference variable (choose its type and name).
- Instantiate the object (create it with
new). - Initialize the variable (store the reference in the variable).
Combined example:
String city = new String("Boston");
Stringis the class/type.cityis the reference variable.new String("Boston")creates a newStringobject using a constructor.
Constructors: what they are and how you recognize them
A constructor is like a method used only for setting up a new object. It has:
- The same name as the class
- No return type (not even
void)
Example constructors you might see:
new String("hi")
Many classes have multiple constructors (this is called overloading—same name, different parameter lists). You choose the one that matches the arguments you provide.
Storing objects: reference semantics in practice
Consider:
String a = new String("AP");
String b = a;
After b = a;, there is still only one String object created by new. Both a and b refer to that same object.
This becomes especially important later with mutable objects (objects that can change). Many objects you meet early—like String—are immutable, meaning their contents don’t change after creation. Even so, understanding reference assignment now prevents big confusion later.
null: a reference that points to “no object”
A reference variable can hold null, meaning it doesn’t refer to any object.
String s = null;
If you try to call a method on null, you get a NullPointerException at runtime:
System.out.println(s.length()); // crashes: s is null
In AP CSA questions, null often appears in code-tracing problems. Your job is to notice whether a reference is null before a method call.
Creating objects without new (common special case: String literals)
You will also see:
String greeting = "hello";
This still results in a String object, but Java allows a shorthand for strings called a string literal. For AP CSA, you should be comfortable with both forms:
String s = "hi";String s = new String("hi");
They can behave differently with == (identity), which is another reason .equals(...) is preferred for content comparison.
Example: object creation and method use
String word = new String("computer");
int len = word.length();
System.out.println(len); // 8
The flow is:
- Create a
Stringobject. - Store its reference in
word. - Call a method on that object using
word.length().
Exam Focus
- Typical question patterns:
- Determine what objects are created and which variables refer to them after a sequence of assignments.
- Trace code involving
nulland predict whether it throws an exception. - Choose the correct constructor call based on parameter types and count.
- Common mistakes:
- Thinking
b = a;copies an object rather than copying the reference. - Calling a method on a reference that might be
null. - Confusing constructors with regular methods (constructors have no return type and match the class name).
- Thinking
Calling a Void Method
A method is a named block of code that performs an action. A void method is a method that performs an action but does not return a value back to where it was called. In Java, its return type is void.
Void methods matter because many actions you want a program to do are “do something” actions rather than “compute and give me a value.” Printing to the console, updating an object, or displaying something on a screen are all typical void-method behaviors.
How calling a method works (the big picture)
When you call a method on an object, you are:
- Choosing which object should perform the action.
- Choosing which method to run.
- (Sometimes) providing arguments (inputs) for the method.
- Letting Java run the method body.
- If the method is non-void, receiving a return value; if it is void, continuing without a value.
For a void method, step 5 is: “there is no value produced.”
Syntax for calling a void method
A void method call is a complete statement by itself:
objectReference.voidMethodName();
Because there is no returned value, you cannot meaningfully “use it inside an expression” (like in math or concatenation).
Example: printing with System.out.println
System.out.println(...) is a method call you’ll use constantly. println is a void method—it prints something and returns nothing.
System.out.println("Hello!");
Even though this call looks special, it follows the same dot-notation idea:
System.outis an object (aPrintStream).printlnis a method you call on that object.
What goes wrong: treating void like it returns a value
A very common error is trying to store the “result” of a void method:
int x = System.out.println("Hi"); // does not compile
This fails because println doesn’t produce an int (or any value). On AP multiple-choice questions, you may be asked which line causes a compile-time error—this is a classic pattern.
Example: a typical custom void method
Even before you write your own classes, you might see small helper methods in a free-response style setting (or practice code) such as:
public class Greeter {
public static void greet() {
System.out.println("Welcome!");
}
}
Call:
Greeter.greet();
This is a static method call (called on the class name, not an instance). Unit 1 primarily emphasizes calling methods; whether they’re static or instance methods depends on the class (for example, Math.random() is static).
Exam Focus
- Typical question patterns:
- Identify whether a method is void or non-void based on a header/signature.
- Predict console output from sequences of
printlncalls. - Spot compile-time errors when a void method call is used where a value is required.
- Common mistakes:
- Writing code like
x = obj.doSomething();whendoSomethingis void. - Forgetting semicolons after a method call statement.
- Confusing instance calls (
obj.method()) with static calls (ClassName.method()) in questions that mix both.
- Writing code like
Calling a Void Method With Parameters
A method parameter is a variable in the method definition that will receive a value when the method is called. An argument is the actual value you pass in the call. Many void methods need parameters because they need details about what action to perform.
For example, println needs to know what to print, so you pass an argument:
System.out.println("AP CSA");
Why parameters matter
Parameters make methods reusable. Instead of writing separate methods like printHello() and printGoodbye(), you can write one method that takes the message to print. In object-oriented programming, parameters also let you customize how an object behaves for a particular call.
How parameter passing works (what AP expects)
When you call a method with parameters, Java evaluates each argument expression first, then passes the resulting values into the method.
Key points you should know at this level:
- The number of arguments must match the number of parameters.
- The types must be compatible (an
intargument goes to anintparameter, aStringto aString, etc.). - Arguments are matched to parameters by position (first to first, second to second).
Syntax
objectReference.voidMethodName(arg1, arg2, ...);
Example: a void method with one parameter
public class Messenger {
public static void announce(String msg) {
System.out.println("Announcement: " + msg);
}
}
Call:
Messenger.announce("Test on Friday");
// Output: Announcement: Test on Friday
Here, msg is the parameter; "Test on Friday" is the argument.
Example: a void method with multiple parameters
public class Formatter {
public static void printSum(int a, int b) {
System.out.println(a + b);
}
}
Call:
Formatter.printSum(7, 5); // Output: 12
Expressions as arguments
Arguments don’t have to be simple literals or variables; they can be expressions:
int x = 10;
Formatter.printSum(x, x + 3); // Output: 23
Java evaluates x (10) and x + 3 (13), then the method prints 23.
What goes wrong: argument/type mismatch and wrong method overload
Two very common compile-time issues:
- Wrong number of arguments
Formatter.printSum(4); // does not compile (needs 2 ints)
- Wrong types
Formatter.printSum("4", "5"); // does not compile (Strings are not ints)
If a class has overloaded methods (same name, different parameter lists), Java chooses the version whose parameter types best match your arguments. AP questions sometimes test whether you can identify which overload gets called.
A note on side effects
Void methods often cause side effects—observable changes that aren’t returned as a value. Printing is a side effect. Modifying an object is a side effect. In later units, you’ll see many void methods that change an object’s internal state.
Exam Focus
- Typical question patterns:
- Determine which method is called when multiple overloaded versions exist.
- Trace output when method calls include expression arguments.
- Identify compile-time errors from wrong argument count/types.
- Common mistakes:
- Mixing up “parameter” (in the method header) vs. “argument” (in the call).
- Assuming arguments are matched by name rather than by position.
- Forgetting that expressions are evaluated before being passed to the method.
Calling a Non-Void Method
A non-void method returns a value to the code that called it. Its method header lists a return type other than void, such as int, double, boolean, or String.
Non-void methods matter because they let you compute results and use them to make decisions, build new values, or store data. Many AP CSA questions involve chaining and combining returned values from String methods, numeric methods, and library methods like Math.random().
Return values: how to think about them
When you call a non-void method, the method call itself becomes an expression that has a value. That means you can:
- Store it in a variable
- Use it in a larger expression
- Use it in a condition
- Pass it as an argument to another method
Conceptually:
- Evaluate the receiver object (the thing before the dot), if any.
- Evaluate the arguments.
- Run the method.
- Replace the method call with its returned value.
Syntax patterns you should recognize
Store the result:
int n = str.length();
Use directly in an expression:
int total = str.length() + 5;
Use in a condition:
if (str.length() > 0) {
System.out.println("Not empty");
}
Pass as an argument:
System.out.println(str.substring(0, 2));
Example: common String non-void methods
String is central in Unit 1 because it provides many easy-to-test non-void methods.
length()returns anintnumber of characters.substring(beginIndex, endIndex)returns a newStringcontaining characters frombeginIndexup to (but not including)endIndex.indexOf("x")returns anintindex of the first occurrence (or -1 if not found).
Worked example:
String s = "program";
int a = s.length(); // 7
String b = s.substring(0, 4); // "prog"
int c = s.indexOf("g"); // 3
System.out.println(a);
System.out.println(b);
System.out.println(c);
Output:
7
prog
3
Important detail: many String methods do not modify the original string because String is immutable. Instead, they return a new String.
Chaining non-void method calls
Because non-void method calls produce values, you can call another method on the returned object (if the return type is an object type).
Example:
String s = "Hello";
String t = s.substring(1).toUpperCase();
System.out.println(t); // "ELLO"
How to read this:
s.substring(1)returns a newString("ello").- On that returned
String, calltoUpperCase(), producing "ELLO".
Chaining is common in AP multiple-choice code tracing. The biggest risk is losing track of types—always ask: “What type does this method return?” That tells you what can come next.
Example: Math.random() and using returned values
Math.random() is a static non-void method that returns a double value greater than or equal to 0.0 and less than 1.0.
double r = Math.random();
System.out.println(r);
In AP CSA, you often use it to generate an integer in a range. The key idea is: because it’s non-void, you can multiply and cast/truncate.
Example: integer from 0 to 5 inclusive (6 possibilities):
int x = (int) (Math.random() * 6);
Math.random()returns adoublein [0.0, 1.0).- Multiplying by 6 gives [0.0, 6.0).
- Casting to
inttruncates the decimal part, producing 0, 1, 2, 3, 4, or 5.
If you wanted 1 to 6 instead:
int die = (int) (Math.random() * 6) + 1;
This pattern is frequently assessed.
What goes wrong: ignoring a return value vs. needing to use it
You can call a non-void method and ignore its returned value:
"hello".toUpperCase(); // legal, but the result is thrown away
But it often signals a logic mistake. For immutable objects like String, ignoring the return value means you didn’t save the changed version.
Common bug:
String s = "hello";
s.toUpperCase();
System.out.println(s); // still "hello"
Correct approach:
String s = "hello";
s = s.toUpperCase();
System.out.println(s); // "HELLO"
Non-void methods in expressions: order and parentheses
When method calls appear inside larger expressions, Java follows standard precedence rules and evaluates method-call expressions to values. Parentheses can clarify intent.
Example:
String s = "abcde";
int result = s.substring(1, 4).length();
System.out.println(result); // 3
substring(1, 4)returns "bcd".length()returns 3
If you struggle with such problems, annotate each sub-expression with its type and value.
Exam Focus
- Typical question patterns:
- Trace code that uses
Stringmethods and determine the final value or output. - Use returned values in expressions/conditions (including chained calls).
- Apply
Math.random()patterns to generate integers in a range.
- Trace code that uses
- Common mistakes:
- Off-by-one errors with
substring(begin, end)(end index is exclusive). - Forgetting
Stringis immutable and expecting methods liketoUpperCase()to modify the original. - Misunderstanding
Math.random()range and placing the cast in the wrong spot (casting too early changes the distribution).
- Off-by-one errors with