AP® · Java
AP® Computer Science A
All four College Board units, the five computational thinking practices, and the Java Quick Reference: built for the 42 MC and the 4 FRQs.
Start Unit 1 free. Unit 1: Using Objects and Methods is open to everyone, no account needed. Other topics are locked.
Unit 1: Using Objects and Methods
THE BIG PICTURE. Unit 1 (15–25%) is the foundation of the AP Computer Science A course: primitive data types, variables, expressions, arithmetic, casting, the String class, output, and how to USE classes and methods that someone else has written. You learn Java's vocabulary and grammar; later units add control flow (Unit 2), class design (Unit 3), and collections (Unit 4).
PRIMITIVE TYPES
Java distinguishes between primitive types (built-in, stored directly) and reference types (objects, stored by reference).
The three primitive types tested on the exam:
- int: 32-bit signed integer. Range to (about ).
- double: 64-bit floating-point number (decimals). Default for decimal literals like 3.14.
- boolean: true or false. No numeric conversion in Java.
- Java also has char, long, short, byte, and float, but the College Board places these outside the scope of the AP course and exam.
Declaration and initialization:
int count = 0;
double pi = 3.14159;
boolean isReady = true;A variable must be declared with a type before use; once declared, the type cannot change.
Primitive vs reference variables A primitive variable stores its value. A reference variable stores an arrow to an object, so two variables can share one object (aliases), and a null reference points to nothing.
ARITHMETIC EXPRESSIONS
Operators: +, -, *, /, % (modulus, remainder).
Critical rule: integer division. When BOTH operands are int, / discards the fractional part
int x = 7 / 2; // x is 3, not 3.5
double y = 7.0 / 2; // y is 3.5 (double promotion)Modulus (%): returns the remainder after division.
17 % 5 = 2(because 17 = 3 × 5 + 2).12 % 4 = 0(12 is evenly divisible by 4).- Useful for: testing divisibility (
n % 2 == 0checks if even); extracting digits (n % 10gives the ones digit).
Order of precedence (high to low)
1. Parentheses.
2. *, /, % (left-to-right).
3. +, - (left-to-right).
4. Assignment (=) happens last: the whole right side is evaluated, then stored in the variable on the left.
Compound assignment: x += 5 is shorthand for x = x + 5. Similarly -=, *=, /=, %=.
Increment/decrement: x++ and x-- (post-increment/decrement); ++x and --x (pre). For AP, only the statement-level postfix form (x++;) is tested; the prefix form and use inside larger expressions are outside the scope of the exam.
CASTING AND NUMERIC PROMOTION
When operands of different types are mixed, Java AUTOMATICALLY promotes:
- int + double → double (the int is promoted to double).
- Result type matches the "wider" operand.
Explicit casting with (type) overrides
double d = 7.8;
int i = (int) d; // i is 7 (truncates toward zero, does NOT round)(int) 7.8 gives 7. (int) -7.8 gives -7. Casting truncates, does not round. To round to the nearest integer, the AP idiom is (int) (x + 0.5) for non-negative x (or (int) (x - 0.5) for negative x). Real Java also has Math.round(), but it is not on the AP Java Quick Reference.
Casting double to int loses precision. Casting int to double is safe (no information loss).
Common bug: integer division before assigning to double
double avg = sum / count; // if sum and count are int, integer division happens BEFORE the assignment
double avg = (double) sum / count; // forces double divisionWORKED EXAMPLE: PREDICT THE VALUE (MC STYLE)
Evaluate each expression. Apply precedence, work left to right within a level, and track the TYPE at every step.
| Expression | Steps | Value |
|---|---|---|
7 / 2 * 2.0 | 7 / 2 is int division, 3; then 3 * 2.0 | 6.0 |
2.0 * 7 / 2 | 2.0 * 7 is 14.0; then 14.0 / 2 | 7.0 |
(double) (7 / 2) | parentheses first give 3; the cast makes it 3.0 | 3.0 |
(double) 7 / 2 | the cast applies to 7 only: 7.0 / 2 | 3.5 |
(int) 9.99 + 1 | the cast truncates 9.99 to 9; then add 1 | 10 |
(int) (2.6 + 0.5) | 3.1, truncated (the AP rounding idiom) | 3 |
17 % 5 + 17 / 5 | 2 + 3 | 5 |
- Lesson 1: the same numbers give 6.0 or 7.0 depending on whether the int division happens before a double enters the expression.
- Lesson 2: a cast applies only to the value right after it.
(double) (7 / 2)is 3.0 because the division already discarded the .5.
CASE STUDY: THE VIDEO THAT OUTGREW AN INT (2014)
A Java int can hold at most Integer.MAX_VALUE, which is 2,147,483,647. YouTube originally counted views with a 32-bit signed integer, the same size as a Java int. In early December 2014, Psy's 2012 video "Gangnam Style" became the first video to pass that limit. YouTube announced that it had switched to a 64-bit counter (maximum over 9 quintillion), and the company told reporters it had seen the milestone coming months earlier and upgraded in advance.
- Concept: integer overflow (CED 1.5). In Java,
Integer.MAX_VALUE + 1does not crash; it wraps around toInteger.MIN_VALUE, which is -2,147,483,648. - What it shows: choosing a type is a prediction about the largest value a program will ever need.
- Exam link: when an int expression goes out of range, the result is still a valid int, just not the value you expected.
STRINGS
A String is a sequence of characters (an OBJECT, not a primitive). Created with double quotes:
String name = "Alice";String concatenation with +
String greeting = "Hello, " + name + "!"; // "Hello, Alice!"
int age = 17;
String s = "Age: " + age; // "Age: 17" (int auto-converted to String)Mixed expressions: if either operand is a String, + concatenates. Otherwise, arithmetic
"sum: " + 3 + 4 // "sum: 34" (left-to-right: concat first)
"sum: " + (3 + 4) // "sum: 7" (parens force arithmetic)
1 + 2 + "result" // "3result" (numbers added, then concat)String methods (memorize the AP-tested ones):
length(): number of characters."hello".length()is 5.substring(start): from index start to end."hello".substring(2)is "llo".substring(start, end): from start INCLUSIVE to end EXCLUSIVE."hello".substring(1, 4)is "ell".indexOf(str): returns first index of str, or-1if not found.equals(other): true if equal. ALWAYS use.equals(), NEVER==for Strings.compareTo(other): returns negative if this < other, 0 if equal, positive if this > other (lexicographic).
Indexing: strings are 0-indexed. To get the single character at index i as a String, use substring(i, i + 1): "hello".substring(0, 1) is "h"; "hello".substring(4, 5) is "o". "hello".substring(5, 6) throws StringIndexOutOfBoundsException. (Real Java also has charAt(i), which returns a char, but it is not on the AP Java subset.)
Strings are IMMUTABLE. s.substring(0, 3) returns a NEW String; it does not modify s. You must reassign: s = s.substring(0, 3);.
String indexes and substring Indexes run from 0 to length() - 1. substring(from, to) includes from and excludes to, so its length is to - from.
Strings are immutable String methods return new Strings and never change the original. Only an assignment moves the variable to the new String.
WORKED EXAMPLE: FRQ Q1 PART B WARM-UP (STRING METHODS)
Write a method initials that takes a name made of a first and last name separated by one space (for example "Grace Hopper") and returns the two initials ("GH").
public static String initials(String fullName)
{
int space = fullName.indexOf(" ");
String first = fullName.substring(0, 1);
String last = fullName.substring(space + 1, space + 2);
return first + last;
}- Step 1, find the landmark.
indexOf(" ")returns 5 for "Grace Hopper". - Step 2, take one-letter substrings.
substring(0, 1)is "G". The last name starts at indexspace + 1, which is 6, sosubstring(6, 7)is "H". - Step 3, return, do not print. The method must
returnthe String; printing it instead does not give the caller a value. - Classic slip:
substring(space, space + 1)returns the space itself, " ".
PRACTICE: WHAT DOES EACH CALL RETURN?
With String w = "banana";
| Call | Result |
|---|---|
w.length() | 6 |
w.substring(3) | "ana" |
w.substring(1, 3) | "an" |
w.indexOf("an") | 1 (the first match) |
w.indexOf("x") | -1 |
w.substring(2, 2) | "" (the empty String) |
w.substring(0, 7) | throws StringIndexOutOfBoundsException |
w.compareTo("apple") > 0 | true ("b" comes after "a") |
w.equals("Banana") | false (case matters) |
OBJECTS, CLASSES, AND METHODS (USAGE)
A class is a blueprint; an object is an instance. Math is a class; Math.sqrt(16) calls the static sqrt method.
Static methods are called on the CLASS (Math.sqrt(16)).
Instance methods are called on an OBJECT (name.length()).
Creating objects with new:
String s = new String("hello"); // explicit creation (rarely needed for String)The Math class (memorize for AP):
Math.abs(x): absolute value.Math.pow(base, exp):base^exp(returns double).Math.sqrt(x): square root.Math.random(): random double in [0.0, 1.0).Math.PIandMath.Eexist in real Java but are not on the Quick Reference; exam code that needs pi defines its own constant.
Random numbers (typical pattern): to generate a random int in [a, b] inclusive
int n = (int) (Math.random() * (b - a + 1)) + a;For a=1, b=6 (dice): (int) (Math.random() * 6) + 1 gives 1-6.
CALLING METHODS
Methods may have parameters (input) and return values (output).
int x = Math.abs(-10); // x is 10
double d = Math.sqrt(25); // d is 5.0
String first = name.substring(0, 1); // returns "A" (name unchanged)Method signature: name + parameter types. Math.abs(int) and Math.abs(double) are different overloads (both are on the Java Quick Reference).
Return value vs side effect: most AP methods return values. Some, like System.out.println(x), have a side effect (printing) and a void return type.
void methods return no value
System.out.println("Hello"); // prints, returns nothingOUTPUT
System.out.println(x): prints x then a newline.
System.out.print(x): prints x without newline.
Common gotchas:
- Strings inside print need to be concatenated:
System.out.println("count: " + count); - Inserting a newline mid-string:
"\n"or use multiple println calls.
EXAM CONNECTIONS. Unit 1 generates many MC items testing: integer division gotchas, type casting, String method usage, arithmetic operator precedence. FRQ Q1 (Methods and Control Structures) requires calling String methods. Memorize: integer division behavior; % for divisibility/digits; String's length, substring, indexOf, equals; Math methods. ALWAYS use .equals() for String comparison, never ==.
Key Terms
Primitive Type
Built-in Java type stored directly in memory. AP tests: int (32-bit integer), double (64-bit floating-point), boolean (true/false). Other Java primitives (char, long, etc.) are outside the AP exam scope.
Reference Type
Type that stores a reference to an object (not the object itself). Strings, arrays, ArrayLists, user-defined classes. 'null' is the absence of a reference.
int
32-bit signed integer. Range to (~). Default integer type.
double
64-bit floating-point number. Default decimal literal type (3.14 is a double, not a float).
boolean
Type that holds true or false. NOT convertible to/from numbers in Java (unlike C/Python).
Integer Division
When BOTH operands are int, '/' discards the fractional remainder. '7 / 2' is 3, not 3.5. To get double division, cast one operand: '(double) 7 / 2' is 3.5.
Modulus (%)
Returns remainder after integer division. '17 % 5' is 2. Useful for divisibility ('n % 2 == 0' tests even) and extracting digits ('n % 10' gets ones digit).
Casting
Explicit type conversion: '(int) 7.8' is 7 (TRUNCATES, does not round). '(double) 5' is 5.0. Use to override automatic promotion or to assign a wider type to a narrower one.
Truncation
Discarding the fractional part when casting double to int. '(int) 7.8' is 7. '(int) -7.8' is -7 (toward zero, NOT toward negative infinity).
String
Object representing a sequence of characters. Created with double quotes: "hello". IMMUTABLE: methods return NEW strings rather than modifying the original.
String Concatenation
Combine strings with '+'. If either operand is a String, '+' concatenates. Numeric values auto-convert: "Age: " + 17 is "Age: 17".
String Immutability
String objects cannot be modified after creation. 's.substring(1)' returns a new String; 's' is unchanged unless reassigned: 's = s.substring(1);'.
String.length()
Returns number of characters as int. '"hello".length()' is 5. Note: methods have parentheses; arrays use .length without ().
String.substring(start, end)
Returns substring from index start INCLUSIVE to end EXCLUSIVE. '"hello".substring(1, 4)' is "ell". The single-arg version 'substring(start)' goes to the end.
String.indexOf(str)
Returns the first index where str is found, or -1 if not found. '"hello".indexOf("ll")' is 2. '"hello".indexOf("x")' is -1.
String.equals(other)
Tests if two strings have the same characters. ALWAYS use this, NEVER '=='. '==' compares object references; 'equals' compares values.
Math.random()
Returns a random double in [0.0, 1.0). To get an int in [a, b] inclusive: '(int) (Math.random() * (b - a + 1)) + a'.
Math Class Methods
abs, pow, sqrt, random (the four on the Quick Reference). All static (called on Math class). Memorize signatures and behavior.
System.out.println
Prints argument followed by newline. 'System.out.print' omits the newline. Concatenate strings and values with '+'.
Static Method
Method called on the class itself, not on an instance. 'Math.sqrt(16)' uses the static 'sqrt' method of the 'Math' class.
Instance Method
Method called on an object instance. 's.length()' calls 'length' on the String object 's'.
Exam Tips
- Integer division is a constant exam trap: '7 / 2' is 3, not 3.5. Cast one operand to double for decimal results.
- Modulus ('%') for divisibility tests ('n % 2 == 0' for even) and digit extraction ('n % 10' for ones digit; 'n / 10' to remove ones digit).
- Casting truncates, does not round. '(int) -7.8' is -7. To round a non-negative x, use the AP idiom '(int) (x + 0.5)'.
- ALWAYS use '.equals()' for String comparison, never '=='. '==' compares references, not contents.
- Strings are immutable: methods like 'substring()' return NEW strings; you must reassign to keep changes.
- substring(start, end): start INCLUSIVE, end EXCLUSIVE. Length of result = end - start. Easy to off-by-one.
- Memorize Math methods: abs, pow, sqrt, random. 'Math.random()' returns [0.0, 1.0); use the standard pattern for random integers.
- Java Quick Reference is provided on the exam: includes Math methods, String methods, ArrayList methods. You don't need to memorize signatures perfectly but should understand behavior.
Now practice this topic
Test yourself on what you just read.
Ready to keep going?
That was the free first unit of the AP® Computer Science A Course Companion. Unlock the complete guide to continue with the rest of the course.
- All 5 topics with full study notes
- 114 flashcards
- 86 practice questions with explanations
- 20 free-response problems with worked solutions
- 93 key terms
$24.99 one-time, 12 months of access.
Taking more than one course? Student Pass: up to 3 guides, $49.99 · Platinum Unlimited: every guide, $74.99.
Already bought it? Sign in
The Prep Den AP® Computer Science A study guide is a complete companion for revising the course: topic-by-topic study notes, interactive flashcards, practice quizzes with worked explanations, a key-terms bank, and exam-technique tips. The first unit above is free to use; the full guide unlocks every topic.
Also searched as: AP Computer Science A study guide, AP CSA study guide, AP CS A study guide, AP Comp Sci A study guide, AP Computer Science A quiz, AP CSA quiz, AP CS A quiz, AP Comp Sci A quiz, AP Computer Science A practice quiz, AP CSA practice quiz, AP CS A practice quiz, AP Comp Sci A practice quiz, AP Computer Science A practice questions, AP CSA practice questions.