What is AP Computer Science A unit 1?
Unit 1 covers the core mechanics of Java that every other unit builds on. You start with how algorithms work and how Java turns source code into a running program, then move through variables, expressions, assignment, and casting. The second half of the unit shifts to object-oriented thinking: what a class is, how to create objects with constructors, and how to call instance and class methods. The Math and String classes give you concrete practice with all of these ideas.
Unit 1 teaches you to write and trace basic Java programs using variables, arithmetic expressions, object creation, and method calls. The key skill is predicting exactly what value a variable holds or what output a program produces after each statement executes.
Primitive types and arithmetic
Java has three primitive types you need for this course: int, double, and boolean. Arithmetic follows operator precedence (*, /, % before +/-), and dividing two ints drops the decimal. Casting with (int) or (double) lets you convert between types, but casting a double to an int truncates, it does not round.
Classes, objects, and constructors
A class is a blueprint; an object is a specific instance created from that blueprint. You create objects with the new keyword and a constructor call, like new String("hello"). A reference variable stores the memory address of the object, not the object itself. Calling a method on a null reference causes a NullPointerException.
Math and String methods
Math class methods (Math.abs, Math.pow, Math.sqrt, Math.random) are static, so you call them on the class name. String methods (length, substring, indexOf, equals, compareTo) are instance methods called on a String object. Strings are immutable: methods return new String objects and never change the original.
Everything in Java is either a primitive value or an object referenceThe single most important distinction in Unit 1 is the difference between primitive types (int, double, boolean) and reference types (String, Math, any class). Primitives store their value directly in the variable. Reference variables store a pointer to an object in memory. This distinction explains casting behavior, NullPointerException, String immutability, and how arguments are passed to methods using call by value. Keep this mental model active as you trace every code segment in the unit.
Unit 1 review notes
1.1
Algorithms, compilation, and error types
An algorithm is a step-by-step process where sequencing matters: each step runs one at a time in order. Java source code is written in a text editor or IDE, then a compiler translates it into a form the computer can run. The compiler catches some errors before the program runs, but not all of them.
- Syntax error: A violation of Java language rules caught by the compiler before the program runs; for example, a missing semicolon or mismatched brace.
- Logic error: A mistake in the algorithm that causes wrong output; the program compiles and runs but produces an unexpected result. Found only through testing.
- Run-time error: An error that occurs during execution and typically terminates the program abnormally; for example, dividing an int by zero.
- Exception: A specific type of run-time error, such as ArithmeticException or NullPointerException, that interrupts normal program flow.
- IDE: An integrated development environment that provides tools to write, compile, and run code in one place.
Given a short Java program with a missing semicolon, an incorrect formula, and a divide-by-zero, can you identify which error is a syntax error, which is a logic error, and which is a run-time error?
| Error type | When detected | Example |
|---|
| Syntax error | Compile time | Missing semicolon, unclosed brace |
| Logic error | Testing (not compiler) | Wrong formula produces bad output |
| Run-time error | During execution | Integer divide by zero |
| Exception | During execution | NullPointerException, ArithmeticException |
1.2
Variables and primitive data types
A variable is a named storage location whose value can change while the program runs. Every variable has a declared type. The three primitive types in AP CSA are int (whole numbers), double (real numbers), and boolean (true or false). Reference types, like String, store a pointer to an object rather than the value itself. You must initialize a variable before using it in an expression.
- int: Stores whole-number values; arithmetic between two ints produces an int result.
- double: Stores real-number values; any arithmetic involving at least one double produces a double result.
- boolean: Stores only true or false; used in conditions and logical expressions.
- Reference type: A type whose variable holds a memory address pointing to an object, not the object's value directly. String is the main reference type in Unit 1.
- Variable declaration: Syntax: type variableName; or type variableName = value; The variable must be initialized before use.
Write a declaration for each of the three primitive types and one reference type. Then identify which type you would use to store a student's GPA, a count of items, and a flag for whether a user is logged in.
| Type | Category | Example values |
|---|
| int | Primitive | 0, -5, 1000 |
| double | Primitive | 3.14, -0.5, 2.0 |
| boolean | Primitive | true, false |
| String | Reference | "hello", "AP CSA" |
1.3
Expressions, output, and operator precedence
System.out.print displays output and keeps the cursor on the same line; System.out.println moves to a new line after printing. Arithmetic expressions follow precedence rules: *, /, and % evaluate before + and -. When both operands are int, division truncates the decimal. Mixing an int and a double promotes the result to double. The + operator concatenates strings when at least one operand is a String.
- System.out.println vs System.out.print: println adds a newline after output; print does not. Both accept strings, numbers, and expressions.
- Integer division: 7 / 2 evaluates to 3, not 3.5, because both operands are int. The fractional part is discarded.
- Remainder operator %: 7 % 2 evaluates to 1. Useful for checking divisibility or cycling through a range.
- Operator precedence: *, /, % are evaluated before + and -. Use parentheses to override the default order.
- String concatenation: "Score: " + 95 produces "Score: 95". A primitive concatenated with a String is implicitly converted to a String.
Predict the output of: System.out.println(7 / 2 + " " + 7 % 2 + " " + 7.0 / 2);
1.4
Assignment, casting, and variable ranges
The assignment operator = evaluates the right-hand expression first, then stores the result in the left-hand variable. The value must be a compatible type. Casting with (int) or (double) converts between primitive types explicitly. Casting a double to an int truncates toward zero. Widening from int to double happens automatically. Integer overflow occurs when an int expression exceeds Integer.MAX_VALUE or goes below Integer.MIN_VALUE, producing an unexpected in-range result. Round-off error occurs when a double value cannot be represented exactly in memory.
- Assignment operator =: Stores the value of the right-hand expression into the left-hand variable. Not equality comparison.
- (int) cast: Truncates the decimal part of a double: (int) 3.9 produces 3, not 4.
- Widening conversion: An int is automatically promoted to double when needed, such as in mixed arithmetic or assignment to a double variable.
- Integer overflow: When an int result exceeds Integer.MAX_VALUE (about 2.1 billion), it wraps around to a negative value instead of throwing an error.
- Round-off error: A double cannot always represent a value exactly, so the stored result may differ slightly from the mathematical result.
What does (int)(7.9) evaluate to? What happens if you add 1 to Integer.MAX_VALUE? Explain both results.
1.6
Compound assignment operators
Compound assignment operators combine an arithmetic operation with assignment in one step. x += 5 is equivalent to x = x + 5. The post-increment operator x++ adds 1 to x and stores the result back in x. These operators appear frequently in loop counters and running totals, so tracing the exact value of a variable after each statement is the key skill.
- +=, -=, *=, /=, %=: Each performs the indicated operation on the current variable value and the right-hand operand, then stores the result back in the variable.
- x++ (post-increment): Adds 1 to x and stores the new value in x. In AP CSA, x++ is used as a standalone statement, not inside a larger expression.
- x-- (post-decrement): Subtracts 1 from x and stores the new value in x.
If x = 10, what is x after x *= 3; then x %= 7;? Trace each step.
1.7
APIs, libraries, and documentation
A library is a collection of classes grouped into packages. An API specification tells you how to use those classes without needing to read their source code. Attributes are the data a class stores in variables; behaviors are what the class can do, defined by methods. Comments document code for human readers but are ignored by the compiler. Preconditions state what must be true before a method runs; postconditions state what is guaranteed to be true after it runs.
- API: Application programming interface: documentation that describes a class's attributes and behaviors so you can use it without knowing its internal implementation.
- Single-line comment //: Documents one line; ignored by the compiler.
- Block comment /* */: Documents multiple lines; ignored by the compiler.
- Javadoc comment /** */: Used to generate API documentation; appears before class and method headers.
- Precondition / postcondition: A precondition must be true before a method is called. A postcondition describes what is guaranteed to be true after the method returns.
A method has the precondition that its int parameter must be positive. Who is responsible for ensuring this condition is met before the method is called?
1.9
Method signatures, calling methods, and static methods
A method signature consists of the method name and its ordered list of parameter types. Arguments passed in a method call must match the parameter list in number, order, and compatible type. Void methods do not return a value and cannot be used in an expression. Non-void methods return a value that must be stored or used. Static (class) methods belong to the class, not to any object, and are called using the class name and dot operator, like Math.sqrt(16).
- Method signature: The method name plus the ordered list of parameter types. Return type is not part of the signature.
- Call by value: Arguments are copied into parameters. Changing a parameter inside a method does not affect the original variable.
- Void method: Returns no value; called as a standalone statement. Example: System.out.println("hi");
- Non-void method: Returns a value of the declared return type; the result must be stored or used in an expression.
- Static method: Belongs to the class, not an instance. Called as ClassName.methodName(args). The keyword static appears in the method header.
- Method overloading: Multiple methods share the same name but have different parameter lists. The compiler selects the correct version based on the arguments.
Math.abs is overloaded with versions for int and double. If you call Math.abs(-3), which version runs and what does it return?
| Method type | Called on | Syntax example | Returns value? |
|---|
| Static (class) method | Class name | Math.sqrt(9.0) | Yes (double) |
| Instance method | Object reference | str.length() | Yes (int) |
| Void method | Class or object | System.out.println(x) | No |
1.11
Math class methods
The Math class is in java.lang, so no import is needed. All Math methods are static. The four methods on the Java Quick Reference are Math.abs (int and double versions), Math.pow(base, exponent), Math.sqrt(x), and Math.random(). Math.random() returns a double in [0.0, 1.0). To generate a random int in a range, use the scale-and-shift pattern: (int)(Math.random() * (max - min + 1)) + min for an inclusive range.
- Math.abs(x): Returns the absolute value of x. Works for both int and double arguments.
- Math.pow(base, exp): Returns base raised to the power exp as a double. Math.pow(2, 10) returns 1024.0.
- Math.sqrt(x): Returns the nonnegative square root of x as a double.
- Math.random(): Returns a random double d where 0.0 <= d < 1.0. Cast and scale to get integers in a specific range.
- Scale-and-shift formula: (int)(Math.random() * (max - min + 1)) + min generates a random int from min to max inclusive.
Write an expression that generates a random integer from 1 to 6 inclusive, simulating a die roll.
1.12
Classes, objects, and constructors
A class is the blueprint that defines attributes (instance variables) and behaviors (methods). An object is a specific instance of a class created at runtime. You create an object with the new keyword followed by a constructor call. The constructor's name matches the class name, and constructors can be overloaded. A reference variable stores the memory address of the object. If a reference variable holds null, calling any method on it causes a NullPointerException.
- Class vs object: A class defines the structure; an object is a specific instance with its own attribute values created from that class.
- Constructor: A special method with the same name as the class, called with new to initialize a new object's attributes.
- Constructor overloading: Multiple constructors with different parameter lists allow objects to be created with different initial values.
- Object reference: A reference variable holds the memory address of an object, not the object itself. Two variables can reference the same object.
- null: A special value indicating a reference variable does not point to any object. Calling a method on null causes NullPointerException.
A class Student has two constructors: Student(String name) and Student(String name, int grade). Which constructor runs for new Student("Alex")? What does the reference variable store after this call?
1.14
Calling instance methods
Instance methods are called on a specific object using the dot operator: objectReference.methodName(arguments). Each object runs the method using its own instance variables, so two objects of the same class can return different results from the same method call. A void instance method is called as a standalone statement. A non-void instance method returns a value that must be stored or used. Always verify the reference is not null before calling a method on it.
- Dot operator: Used between an object reference and a method name to call an instance method: myObject.doSomething().
- NullPointerException: Thrown at runtime when you call an instance method on a reference variable that holds null.
- Instance method vs static method: Instance methods require an object; static methods are called on the class name. Both use the dot operator but with different left-hand sides.
If String s = null; what happens when you call s.length()? Name the error and explain why it occurs.
1.15
String objects and String methods
A String is an immutable reference type in java.lang. You can create one with a string literal or with new String(). Because Strings are immutable, methods like substring and toUpperCase return new String objects; they do not modify the original. String indices run from 0 to length() - 1. The five String methods on the Java Quick Reference are length(), substring(from, to), substring(from), indexOf(str), equals(other), and compareTo(other).
- String immutability: Once created, a String's characters cannot change. Methods return new String objects rather than modifying the original.
- length(): Returns the number of characters in the String as an int. "hello".length() returns 5.
- substring(from, to): Returns the substring from index from up to but not including index to. "hello".substring(1, 3) returns "el".
- indexOf(str): Returns the index of the first occurrence of str, or -1 if not found.
- equals(other): Returns true if the two Strings contain the same sequence of characters. Use equals, not ==, to compare String content.
- compareTo(other): Returns a negative int if this String comes before other lexicographically, 0 if equal, positive if after.
For String s = "computer"; what does s.substring(0, 4) return? What does s.indexOf("put") return? What does s.length() return?
Practice AP Computer Science A unit 1 questions
Try AP-style multiple-choice questions and written prompts after you review the notes.
QuestionA robotics team is testing a navigation algorithm using unique Trial IDs. Data set 1 contains the Trial ID and the initialization code text. Data set 2 contains the Trial ID and the NullPointerException logs. Data set 3 contains the Trial ID and the actual final robot coordinates. Data set 4 contains the Trial ID and the expected final robot coordinates. A developer wants to determine which specific initialization code causes the program to crash during execution because an object was never created. Which two data sets must be combined?
Data sets 1 and 2, to link the specific initialization code to the run-time errors encountered.
Data sets 1 and 4, to link the specific initialization code to the expected logic output values.
Data sets 2 and 3, to link the actual final coordinates to the run-time errors encountered.
Data sets 3 and 4, to link the actual final coordinates to the expected logic output values.
QuestionConsider the following method that is intended to read positive integers from a Scanner and return their sum. The input ends when a negative integer or zero is read.
public int sumPositive(Scanner in) {
int sum = 0;
int num = in.nextInt();
while (num > 0) {
/* missing code */
}
return sum;
}
Which of the following can replace /* missing code */ so that the method works as intended?
sum += num; num = in.nextInt();
num = in.nextInt(); sum += num;
sum += num; sum = in.nextInt();
num += sum; num = in.nextInt();
1. This question involves the SimulationLog class, which tracks a sequence of events in a system simulation. The SimulationLog class uses a helper method, getNextEvent, to determine the sequence of events. You will write a constructor and a method in the SimulationLog class.
public class SimulationLog
{
/** The string containing all events, separated by " -> " */
private String log; // To be initialized in part (a)
/** The number of events currently in the log */
private int numEvents; // To be initialized in part (a)
/**
* Initializes the log with the starting event and appends subsequent events
* obtained by calling getNextEvent until a null event is returned.
* Updates log and numEvents as described in part (a).
* Precondition: startEvent is a non-empty string.
*/
public SimulationLog(String startEvent)
{ /* to be implemented in part (a) */ }
/**
* Returns the next event based on the previous event.
* Returns null if there are no more events.
* Precondition: prevEvent is a non-empty string.
*/
public String getNextEvent(String prevEvent)
{ /* implementation not shown */ }
/**
* Returns the number of times the keyword appears in the log.
* Occurrences of keyword are non-overlapping.
* Precondition: keyword is a non-empty string.
*/
public int countKeyword(String keyword)
{ /* to be implemented in part (b) */ }
/* There may be instance variables, constructors, and methods that are not shown. */
}
The helper method getNextEvent returns the next event string based on the current event. Consecutive calls to getNextEvent are guaranteed to eventually return null, ensuring the constructor terminates.
Example 1
Consider the following calls to getNextEvent made within the constructor. The return value of each call is used as the argument for the next call.
| Method Call | Return Value |
|---|
| getNextEvent("boot") | "check" |
| getNextEvent("check") | "run" |
| getNextEvent("run") | "end" |
| getNextEvent("end") | null |
Based on these return values, a call to new SimulationLog("boot") should set the instance variable log to "boot -> check -> run -> end" and set numEvents to 4.
Example 2
Consider the following calls to getNextEvent:
| Method Call | Return Value |
|---|
| getNextEvent("alert") | "notify" |
| getNextEvent("notify") | null |
Based on these return values, a call to new SimulationLog("alert") should set the instance variable log to "alert -> notify" and set numEvents to 2.
Complete the SimulationLog constructor.
/**
* Initializes the log with the starting event and appends subsequent events
* obtained by calling getNextEvent until a null event is returned.
* Updates log and numEvents as described in part (a).
* Precondition: startEvent is a non-empty string.
*/
public SimulationLog(String startEvent)
Example 1
Assume the instance variable log contains "boot -> check -> run -> end".
| Method Call | Return Value |
|---|
| countKeyword("check") | 1 |
| countKeyword("error") | 0 |
The keyword "check" appears once. The keyword "error" does not appear.
Example 2
Assume the instance variable log contains "test -> retest -> test -> done".
| Method Call | Return Value |
|---|
| countKeyword("test") | 3 |
| countKeyword("retest") | 1 |
The keyword "test" appears in "test", "retest", and "test". Note that "retest" contains "test".
Complete the countKeyword method.
/**
* Returns the number of times the keyword appears in the log.
* Occurrences of keyword are non-overlapping.
* Precondition: keyword is a non-empty string.
*/
public int countKeyword(String keyword)
Take a unit 1 test
A timed, AP-style test built only from unit 1 questions — multiple choice plus free response, scored with AI feedback. Use the standard format or build your own.
Start a unit test