AP CSA Unit 1 - Ultimate Study Guide

AP Computer Science A

Unit 1: Using Objects and Methods

Ultimate Study Guide - 2025-2026 Curriculum

15-17.5% of AP Exam | Foundation for All Units

Unit 1 Overview

Unit 1: Using Objects and Methods introduces the foundational concepts of Java programming. You'll learn how to work with variables, call methods, create objects, and manipulate Strings - skills that form the backbone of every AP CSA program.

Exam Weight: 15-17.5% of Multiple Choice

Unit 1 concepts appear throughout the exam:

  • Variable declarations and data types
  • Calling static and instance methods
  • Creating objects with constructors
  • String manipulation (heavily tested!)
  • Using the Math class

Unit 1 Topic Breakdown

Topic Content Exam Focus
1.1 Introduction to Algorithms, Programming, and Compilers Conceptual MCQ
1.2 Variables and Data Types MCQ, FRQ
1.3 Expressions and Output MCQ, FRQ
1.4 Assignment Statements and Input MCQ, FRQ
1.5 Casting and Range of Variables Heavy MCQ
1.6 Compound Assignment Operators MCQ, FRQ
1.7 Application Program Interface (API) and Libraries Conceptual MCQ
1.8 Documentation with Comments Conceptual
1.9 Method Signatures MCQ, FRQ
1.10 Calling Class (Static) Methods MCQ, FRQ
1.11 Math Class MCQ, FRQ
1.12 Objects: Instances of Classes MCQ
1.13 Object Creation and Storage (Instantiation) MCQ, FRQ
1.14 Calling Instance Methods Heavy MCQ, FRQ
1.15 String Manipulation Heavy MCQ, FRQ

Skills You'll Master

  • Understand what algorithms and programs are
  • Declare and initialize variables of different types
  • Write arithmetic expressions and output results
  • Understand integer division and type casting
  • Read and interpret API documentation
  • Distinguish between class (static) and instance methods
  • Use Math class methods effectively
  • Create objects using constructors
  • Call instance methods on objects
  • Manipulate Strings with built-in methods

Algorithms, Programming, and Compilers

What is an Algorithm?

An algorithm is a step-by-step procedure for solving a problem or accomplishing a task. Algorithms are language-independent - they describe what to do, not how to write it in code.

Algorithm Characteristics
  • Precise: Each step is clearly defined
  • Finite: Has a definite ending
  • Effective: Each step can be performed
  • Input/Output: Takes input and produces output

From Algorithm to Program

// Algorithm: Find the average of two numbers
// 1. Get two numbers
// 2. Add them together
// 3. Divide the sum by 2
// 4. Display the result

// Java Program implementing the algorithm:
int num1 = 10;
int num2 = 20;
double average = (num1 + num2) / 2.0;
System.out.println(average);  // 15.0

What is a Compiler?

A compiler translates your Java source code (.java files) into bytecode (.class files) that can run on the Java Virtual Machine (JVM).

// The compilation process:
//
// YourProgram.java  →  [Compiler]  →  YourProgram.class  →  [JVM]  →  Output
//   (source code)                       (bytecode)

Types of Errors

Error Type When Detected Example
Syntax Error
(Compile-time)
During compilation int x = (missing value)
Runtime Error During execution Division by zero, null pointer
Logic Error Wrong output Using + instead of *

Variables and Data Types

A variable is a named storage location in memory that holds a value. Every variable has a type that determines what values it can hold.

Primitive Data Types (AP Exam Subset)

Type Description Size Example Values
int Integers (whole numbers) 32 bits -5, 0, 42, 1000000
double Decimal numbers 64 bits 3.14, -0.5, 2.0
boolean True or false 1 bit true, false

Reference Types (Objects)

Type Description Example Values
String Text (sequence of characters) "Hello", "AP CSA", ""
Other Objects Instances of classes new Scanner(...), new Random()

Declaring Variables

// Declaration only (gets default value in instance variables)
int age;
double price;
String name;

// Declaration with initialization (required for local variables!)
int age = 17;
double price = 19.99;
String name = "Alice";
boolean isStudent = true;

Variable Naming Rules

Rule Valid Invalid
Must start with letter, $, or _ score, _count 2ndPlace, @name
Can contain letters, digits, $, _ player1, totalScore high-score, my name
Cannot be a reserved word myClass class, int, for
Case sensitive Scorescore -

Naming Conventions

// Use camelCase for variables and methods
int studentAge;
double averageScore;

// Use PascalCase for class names
class StudentRecord { }

// Use ALL_CAPS for constants
final double TAX_RATE = 0.0825;

Primitive vs. Reference Types

Primitive Types

  • Store the actual value
  • Lowercase names (int)
  • No methods
  • Compare with ==

Reference Types

  • Store a reference to an object
  • Capitalized names (String)
  • Have methods
  • Compare content with .equals()

Expressions and Output

Arithmetic Operators

Operator Name Example Result
+ Addition 7 + 3 10
- Subtraction 7 - 3 4
* Multiplication 7 * 3 21
/ Division 7 / 3 2 (integer!)
% Modulus (remainder) 7 % 3 1

Integer Division - The #1 Gotcha!

// When BOTH operands are int, result is int (truncated!)
int a = 7 / 3;       // 2 (not 2.33...)
int b = 5 / 10;      // 0 (not 0.5)

// Even storing in double doesn't help - damage is done!
double d = 7 / 3;    // 2.0 (NOT 2.33...)

// If EITHER operand is double, result is double
double e = 7.0 / 3;  // 2.333...
double f = 7 / 3.0;  // 2.333...

Modulus (%) - Finding Remainders

7 % 3   // 1 (7 = 3x2 + 1)
10 % 5  // 0 (evenly divisible)
3 % 7   // 3 (3 = 7x0 + 3)

// Common uses:
x % 2 == 0   // true if x is even
x % 2 != 0   // true if x is odd
12345 % 10   // 5 (extract last digit)

Output with System.out

// println - prints and moves to next line
System.out.println("Hello");
System.out.println("World");

// print - prints without newline
System.out.print("Hello ");
System.out.print("World");  // Hello World (same line)

// Printing expressions
System.out.println(3 + 4);        // 7
System.out.println("Sum: " + 7);  // Sum: 7

String Concatenation

// + joins strings together
String s = "Hello" + " " + "World";  // "Hello World"

// Watch the order!
System.out.println(1 + 2 + "3");  // "33" (1+2=3, then "3")
System.out.println("1" + 2 + 3);  // "123" (all concatenation)
System.out.println("1" + (2 + 3)); // "15" (parentheses first)

Assignment Statements and Input

Assignment Operator (=)

// = assigns the value on the right to the variable on the left
int x = 10;
x = 20;           // x now holds 20
x = x + 5;        // x now holds 25

Swapping Values

// WRONG - loses the original value of a
int a = 5, b = 10;
a = b;  // a = 10
b = a;  // b = 10 (original 5 is lost!)

// CORRECT - use a temporary variable
int a = 5, b = 10;
int temp = a;  // temp = 5
a = b;         // a = 10
b = temp;      // b = 5

Scanner Input

import java.util.Scanner;

Scanner input = new Scanner(System.in);

System.out.print("Enter your name: ");
String name = input.nextLine();

System.out.print("Enter your age: ");
int age = input.nextInt();

input.close();

Scanner Methods

Method Returns Reads
nextInt() int Next integer
nextDouble() double Next decimal number
next() String Next word (token)
nextLine() String Entire line

Casting and Range of Variables

Implicit Casting - Widening

// int → double happens automatically
int x = 10;
double y = x;  // y = 10.0

Explicit Casting - Narrowing

// double → int requires explicit cast
double x = 9.7;
int y = (int) x;  // y = 9 (TRUNCATED, not rounded!)

double z = -3.9;
int w = (int) z;  // w = -3 (truncates toward zero)
Casting TRUNCATES, Not Rounds!
(int) 3.9   // 3 (not 4!)
(int) 3.1   // 3
(int) -2.9  // -2 (not -3!)

Casting to Fix Integer Division

int num = 7, denom = 3;

double wrong = num / denom;         // 2.0
double right = (double) num / denom;  // 2.333...
double nope = (double) (num / denom); // 2.0 (too late!)

Integer Range and Overflow

// int range: -2,147,483,648 to 2,147,483,647
int max = Integer.MAX_VALUE;  // 2147483647
int min = Integer.MIN_VALUE;  // -2147483648

// Overflow wraps around (no error thrown!)
int x = Integer.MAX_VALUE;
x = x + 1;  // -2147483648 (wraps to MIN_VALUE)

Compound Assignment Operators

Operator Example Equivalent To
+= x += 5; x = x + 5;
-= x -= 3; x = x - 3;
*= x *= 2; x = x * 2;
/= x /= 4; x = x / 4;
%= x %= 3; x = x % 3;

Increment and Decrement

int x = 5;
x++;  // x is now 6 (same as x = x + 1)
x--;  // x is now 5 (same as x = x - 1)

APIs and Libraries

What is an API?

An Application Program Interface (API) is a collection of pre-written classes and methods that you can use in your programs.

Import Statements

import java.util.Scanner;
import java.util.Random;
import java.util.*;  // Import all from java.util

// java.lang is automatically imported (String, Math, Integer, etc.)

AP Exam API Classes

Class Package Purpose
String java.lang Text manipulation
Math java.lang Mathematical operations
Integer java.lang Wrapper for int
Double java.lang Wrapper for double
ArrayList java.util Resizable array

Documentation with Comments

// Single-line comment
int x = 10;  // End of line comment

/* Multi-line comment
   spans multiple lines */

/**
 * Javadoc comment - for documentation
 * @param x the first number
 * @return the result
 */

Preconditions and Postconditions

  • Precondition: What must be true BEFORE the method runs
  • Postcondition: What will be true AFTER the method runs

Method Signatures

Anatomy of a Method Signature

//  access   static?  return   name      parameters
//    ↓        ↓       type      ↓           ↓
    public   static    int     add    (int a, int b)

// More examples:
public void printMessage(String msg)   // void = no return
public double calculateArea(double r) // returns double
public String getName()                // no parameters

Return Types

Return Type Meaning
void Returns nothing
int Returns an integer
double Returns a decimal
boolean Returns true/false
String Returns a String
Parameter vs. Argument
  • Parameter: Variable in method signature (formal parameter)
  • Argument: Value passed when calling (actual parameter)

Calling Class (Static) Methods

Static methods belong to the class itself, not to any specific object. Call them using the class name.

// Calling static methods: ClassName.methodName(arguments)
double root = Math.sqrt(16);       // 4.0
int bigger = Math.max(5, 10);      // 10
double power = Math.pow(2, 3);     // 8.0
int num = Integer.parseInt("42");  // 42

Static vs. Instance Methods

Static Methods

  • Called on the class
  • Math.sqrt(16)
  • Don't need an object

Instance Methods

  • Called on an object
  • str.length()
  • Need an object first

Math Class

Essential Math Methods

Method Description Example Result
Math.abs(x) Absolute value Math.abs(-5) 5
Math.pow(base, exp) Power Math.pow(2, 3) 8.0
Math.sqrt(x) Square root Math.sqrt(16) 4.0
Math.random() Random [0.0, 1.0) Math.random() 0.xxx
Math.pow() Returns double!
int result = Math.pow(2, 3);  // COMPILE ERROR!
int result = (int) Math.pow(2, 3);  // ✔ result = 8

Random Integer Formula

// Random int from min to max (inclusive):
(int) (Math.random() * (max - min + 1)) + min

// Dice roll (1-6)
int dice = (int) (Math.random() * 6) + 1;

Objects: Instances of Classes

What is an Object?

An object is an instance of a class. A class is a blueprint; an object is a specific thing created from that blueprint.

Classes vs. Objects Analogy

Class (Blueprint) Object (Instance)
Cookie cutter Individual cookies
Car design Your specific car
String "Hello", "World"

Object State and Behavior

  • State: The data stored in an object (instance variables)
  • Behavior: What an object can do (methods)

Object Creation (Instantiation)

Creating Objects with new

// Syntax: ClassName objectName = new ClassName(arguments);

Scanner input = new Scanner(System.in);
Random rand = new Random();
String s = new String("Hello");

Constructors

A constructor is a special method that creates and initializes a new object.

Reference Variables and null

String s1 = "Hello";
String s2 = s1;  // s2 points to SAME object as s1

String s3 = null;  // null means "no object"
s3.length();  // NullPointerException!
NullPointerException

Calling a method on null causes a runtime crash!

Calling Instance Methods

// Syntax: objectReference.methodName(arguments)

String s = "Hello";
int len = s.length();           // 5
String upper = s.toUpperCase(); // "HELLO"

void vs. Return Value Methods

// void methods - perform action, return nothing
System.out.println("Hello");

// Return value methods - give back a result
int len = "Hello".length();  // Returns 5
Don't Ignore Return Values!
String s = "hello";
s.toUpperCase();  // Result is lost!
s = s.toUpperCase();  // ✔ s is now "HELLO"

String Manipulation

Strings are immutable - once created, they cannot be changed. String methods return NEW strings.

Essential String Methods

Method Description Example Result
length() Number of characters "Hello".length() 5
substring(start, end) Chars from start to end-1 "Hello".substring(1, 4) "ell"
substring(start) Chars from start to end "Hello".substring(2) "llo"
indexOf(str) First index (-1 if not found) "Hello".indexOf("l") 2
equals(str) Content equality "Hi".equals("hi") false
compareTo(str) Lexicographic comparison "A".compareTo("B") negative

String Indexing

String s = "Hello";
//          01234
// s.length() = 5
// Valid indices: 0, 1, 2, 3, 4
substring(start, end) - End is EXCLUSIVE!
"Hello".substring(1, 3)  // "el" (not "ell"!)

Comparing Strings

Wrong

if (str1 == str2)

✔ Correct

if (str1.equals(str2))

Strings are Immutable!

String s = "Hello";
s.toUpperCase();       // Returns "HELLO" but s unchanged!
s = s.toUpperCase();   // Now s = "HELLO"

Common Exam Traps

1. Integer Division

double avg = sum / count;

double avg = (double) sum / count;

2. String Comparison

if (str1 == str2)

if (str1.equals(str2))

3. substring() End Index

Thinking

"Hello".substring(1,3) → "ell"

✔ Reality

"Hello".substring(1,3) → "el"

4. Casting Truncates

Thinking

(int) 3.9 → 4

✔ Reality

(int) 3.9 → 3

5. Math.pow() Returns double

int x = Math.pow(2, 3);

int x = (int) Math.pow(2, 3);

6. String Immutability

s.toUpperCase();

s = s.toUpperCase();

Practice Questions

Q1: Integer Division

int a = 17, b = 5;
double result = a / b;
System.out.println(result);
B) 3.0
17/5 performs integer division (= 3), then converts to double (3.0)

Q2: String substring()

String s = "computer";
System.out.println(s.substring(3, 6));
B) "put"
Indices 3, 4, 5 (end is exclusive): c(0)o(1)m(2)p(3)u(4)t(5)e(6)r(7)

Q3: Modulus and Division

int x = 47;
System.out.println(x % 10 + x / 10);
B) 11
47 % 10 = 7, 47 / 10 = 4, sum = 11

Q4: Casting

double d = -2.7;
int i = (int) d;
System.out.println(i);
B) -2
Casting truncates toward zero, doesn't round!

Q5: String Concatenation

System.out.println(3 + 4 + "5" + 6 + 7);
B) "7567"
3+4=7, then "7"+"5"="75", "75"+"6"="756", "756"+"7"="7567"

Q6: Math.pow()

System.out.println((int) Math.pow(3, 2) + 1);
C) 10
Math.pow(3, 2) = 9.0, cast to int = 9, 9 + 1 = 10

Q7: indexOf()

String s = "Mississippi";
System.out.println(s.indexOf("ss"));
B) 2
First "ss" starts at index 2: M(0)i(1)s(2)s(3)...

Q8: Random Numbers

int num = (int) (Math.random() * 6) + 1;

What is the range of possible values?

C) 1 to 6
Math.random() * 6 gives [0, 6), cast gives 0-5, +1 gives 1-6

Q9: Static vs Instance

Which correctly calls a method from the Math class?

B) Math.sqrt(16);
Math methods are static - call using the class name.

Q10: String Comparison

String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
B) false, true
== compares references (different objects), equals() compares content

Quick Reference

Data Types

Type Description Example
int Whole numbers 42
double Decimals 3.14
boolean True/false true
String Text "Hello"

String Methods

length() Number of characters
substring(start, end) Chars start to end-1
indexOf(str) First index (-1 if not found)
equals(str) Content equality
compareTo(str) Lexicographic comparison

Math Methods

Math.abs(x) Absolute value
Math.pow(base, exp) Power (returns double!)
Math.sqrt(x) Square root
Math.random() Random [0.0, 1.0)

Final Checklist

  • Integer division truncates - cast to double first
  • Use .equals() for Strings, not ==
  • substring(start, end) - end is EXCLUSIVE
  • Casting truncates toward zero
  • Math.pow() returns double
  • Strings are immutable - reassign to save changes
  • Static: ClassName.method()
  • Instance: object.method()
  • Calling methods on null crashes

AP CSA Unit 1: Using Objects and Methods

Ultimate Study Guide - 2025-2026

© AP CS Exam Prep | Good luck!

Contact form