Unit 1 Knowledge Handout: Using Objects and Methods

This handout follows the current AP CSA course sequence for Unit 1. Use it to review Java foundations, numeric rules, method calls, objects, and String behavior.

1. Algorithms and Compilers

Algorithm

An algorithm is a precise, finite set of steps for solving a problem.

  • Life analogy: Recipes, sheet music, Lego instructions
  • Key characteristics:
    • Clear start and end
    • Every step is precise and unambiguous
    • Completes in a finite number of steps

Compiler

A compiler translates human-readable Java code into executable binary instructions.

Java Source (.java) → [ Compiler ] → Bytecode (.class)
 (Human Readable)     (Strict Check)   (Machine Code)
  • The compiler is extremely strict — any syntax error causes compilation to fail
  • The compiler does not guess what you meant

2. Three Types of Errors

Error TypeWhen It HappensBehaviorAnalogy
Syntax ErrorCompile timeCompiler rejects code, cannot runRecipe with misspellings, can't follow
Logic ErrorRuntimeProgram runs but produces wrong resultRecipe steps correct but too much salt
Runtime ErrorRuntimeProgram crashes mid-executionGame suddenly crashes during play

Examples

// Syntax Error — missing semicolon
System.out.println("Hello")   // ❌ compile error

// Logic Error — runs but gives wrong answer
int average = 10 / 4;         // result is 2, not 2.5
System.out.println(average);  // prints 2 (you probably wanted 2.5)

// Runtime Error — crashes during execution
int x = 5 / 0;                // ❌ ArithmeticException

Remember: The difference between a beginner and an expert isn't making fewer mistakes — it's reading error messages and locating problems faster.


3. Basic Java Program Structure

Every Java program follows a fixed "skeleton":

public class MyFirstProgram {

    public static void main(String[] args) {
        // All execution logic goes here
    }
}

Rules to Remember

RuleExplanation
Case-sensitiveClass and class are different in Java
main method is the entry pointWithout main, the program cannot start
Braces come in pairs{ and } must always be paired and properly nested
Filename = Class nameThe filename must exactly match the public class name

Key Terms

  • Class: The "blueprint" or "container" of a program
  • main method: The "front door" where execution begins
  • Statement: A single executable line, ending with ;

4. Output and Escape Sequences

Two Output Methods

System.out.print("Apple ");    // print without newline
System.out.println("Banana");  // print with newline
MethodEffect
System.out.print(...)Outputs content, cursor stays at the end
System.out.println(...)Outputs content, cursor moves to next line

Escape Sequences

Use the backslash \ to print special characters inside strings:

SequenceMeaning
\nNew line
\"Print a double quote
\\Print a backslash
System.out.println("Red\n\"Blue\"");
// Output:
// Red
// "Blue"

System.out.println("Type \"Y\" to continue");
// Output: Type "Y" to continue

5. Comments

Comments are written for humans — the compiler ignores them completely.

// Single-line comment

/*
   Multi-line comment:
   This spans multiple lines
*/

/**
 * Javadoc comment: used to generate API documentation
 * @param name the student's name
 */
TypeSyntaxUse Case
Single-line// ...Brief explanation
Multi-line/* ... */Longer notes
Javadoc/** ... */Generate API docs

6. Variables and Data Types

Three Elements of a Variable

Type + Name = Value

AP CSA Core Data Types

int score = 100;          // integer (whole number)
double price = 19.99;     // decimal (floating-point)
boolean isReady = true;   // logical (only true or false)
TypeMeaningExample
intInteger (main type for AP CSA)int age = 17;
doubleDecimal (main type for AP CSA)double gpa = 3.5;
booleanLogical valueboolean pass = true;

All 8 Primitive Types in Java (for awareness)

TypeSizeRange / Notes
byte1 byte-128 ~ 127
short2 bytes-32,768 ~ 32,767
int4 bytes-2³¹ ~ 2³¹-1
long8 bytesLarge integers, suffix L (e.g. 100L)
float4 bytesLow-precision decimal, suffix f
double8 bytesStandard decimal (main type for AP CSA)
boolean1 bittrue / false
char2 bytesSingle character, single quotes: 'A'

Variable Naming Rules

Required rules:

  • Allowed characters: letters (a-z, A-Z), digits (0-9), underscore (_)
  • Cannot start with a digit
  • Cannot be a Java reserved keyword (e.g., int, class, double, public)
  • Case-sensitive: age and Age are different variables

Conventions (strongly recommended):

  • camelCase: studentAge, isActive
  • Meaningful names: score is better than s
  • Constants in UPPER_CASE: MAX_SIZE
  • Class names in PascalCase: MyProgram

Keyboard Input with Scanner

Scanner reads values typed by the user. Import the class, create one Scanner connected to System.in, and call the method that matches the expected type.

import java.util.Scanner;

Scanner input = new Scanner(System.in);
int age = input.nextInt();
double price = input.nextDouble();
String word = input.next();

The receiving variable must have a compatible type.


7. Assignment and Arithmetic Rules

The Assignment Operator =

Assignment works right-to-left: evaluate the right side first, then store the result in the left variable.

int score = 10;
score = score + 5;   // compute score + 5 = 15, then store 15 back into score

Variable Independence

int a = 10;
int b = a;    // copy a's value into b
a = 20;       // changing a does NOT affect b
System.out.println(b);  // still 10

Arithmetic Operators

OperatorMeaningExampleResult
+Addition3 + 47
-Subtraction7 - 34
*Multiplication3 * 412
/Division10 / 42 (⚠️ integer division!)
%Modulus (remainder)10 % 31

Integer Division — AP MUST-KNOW 🔥

When two integers divide, the result is always an integer — the decimal part is truncated (not rounded).

System.out.println(10 / 4);      // 2 (not 2.5!)
System.out.println(5 / 2);       // 2
System.out.println(1 / 3);       // 0
System.out.println(10 / 4.0);    // 2.5 (double present → double result)

Operator Precedence

1. ( ) parentheses
2. *, /, % (left to right)
3. +, - (left to right)
System.out.println((2 + 3) * 4);  // 20
System.out.println(10 - 3 * 2);   // 4 (multiplication first)
System.out.println(7 % 3 + 1);    // 2

Type Promotion

When a double is present in an arithmetic expression, the result is automatically promoted to double:

double result = 10 / 4.0;  // 2.5
double result2 = 10.0 / 4; // 2.5

Assignment Compatibility

int x = 5;
double y = x;    // ✅ int → double auto-promotion, y = 5.0

double d = 3.5;
int i = d;       // ❌ compile error! double → int cannot auto-convert

final Constants

A variable declared with final cannot be changed after assignment:

final double PI = 3.14159;
PI = 3.14;  // ❌ compile error!

8. Type Casting

Casting Syntax

(targetType) expression

Casting explicitly tells Java: "I know data might be lost, and I'm okay with that."

Truncation — AP MUST-KNOW 🔥

When casting to int, the decimal part is truncated (not rounded).

System.out.println((int) 3.9);    // 3 (not 4!)
System.out.println((int) -3.8);   // -3 (toward zero)
System.out.println((double) 5);   // 5.0

Cast Precedence Trap — AP MUST-KNOW 🔥

(int) only applies to the value or expression immediately after it:

System.out.println((int) 9.9 * 2);     // 18: (int)9.9 = 9, then 9 * 2
System.out.println((int)(9.9 * 2));    // 19: 9.9*2 = 19.8, truncated to 19
System.out.println((double) 10 / 4);   // 2.5: 10 → 10.0, then 10.0 / 4
System.out.println((double)(10 / 4));  // 2.0: 10/4 = 2, then 2 → 2.0

Common Cast Practice

int x = (int) 7.9;          // 7
int y = (int) -3.8;         // -3
double z = (double) 5;      // 5.0
int a = (int)(8.6 + 0.5);   // 9 (can be used for rounding)

9. Compound Assignment and Increment/Decrement

Compound Assignment Operators

OperatorMeaningEquivalent
x += 5x = x + 5Add and assign
x -= 3x = x - 3Subtract and assign
x *= 2x = x * 2Multiply and assign
x /= 4x = x / 4Divide and assign
x %= 3x = x % 3Modulus and assign
int x = 10;
x += 5;    // x = 15
x *= 2;    // x = 30

int y = 10;
y %= 3;    // y = 1

Increment / Decrement (as standalone statements)

AP CSA only tests these as standalone statements:

x++;    // equivalent to x = x + 1
x--;    // equivalent to x = x - 1
int count = 5;
count++;     // count = 6
count--;     // count = 5
count += 1;  // count = 6 (all three are equivalent)
count = count + 1;  // count = 7

AP Note: The difference between prefix (++x) and postfix (x++) inside complex assignments is NOT a focus of the AP CSA exam.


10. Numeric Range and Overflow

int Memory Specification

  • int uses 4 bytes (32 bits)
  • Range: -2³¹ ~ 2³¹-1 (approx. -2.1 billion ~ 2.1 billion)
  • Maximum value: Integer.MAX_VALUE = 2,147,483,647
  • Minimum value: Integer.MIN_VALUE = -2,147,483,648

Integer Overflow

The number line in a computer is not a straight line — it's a circle:

System.out.println(Integer.MAX_VALUE);          // 2147483647
System.out.println(Integer.MAX_VALUE + 1);      // -2147483648 (overflow!)
System.out.println(Integer.MIN_VALUE - 1);      // 2147483647 (wraps back)

Floating-Point Round-off Error

double cannot represent certain decimal values exactly in binary:

System.out.println(0.1 + 0.2);  // 0.30000000000000004 (not 0.3!)

This is due to binary precision limitations. Be careful with financial calculations.


11. Method Calls and API

What is a Method?

A method is a named, reusable block of code. It can perform a task or return a result.

Method Signature

When reading a signature, ask four questions:

double calcSpeed(int miles)
Return typeMethod nameParameter type
doublecalcSpeedint
  1. Return type? → double
  2. Method name? → calcSpeed
  3. Number of parameters? → 1
  4. Parameter types? → int

Return Value vs void

// Method that returns a value
int result = Math.abs(-5);      // result = 5
double root = Math.sqrt(81);    // root = 9.0

// void method (returns nothing)
System.out.println("Hello");    // no return value
Return TypeMeaning
int / double / boolean etc.Returns a value
voidReturns nothing, only performs an action

A non-void return value must be stored, printed, or used in an expression. A void call cannot be used where Java expects a value.

Arguments and Method Contracts

Arguments must match the parameter list in number, order, and compatible type. A precondition states what must be true before a call; a postcondition states what the method guarantees afterward.

Overloaded Methods

Overloaded methods have the same name but different parameter lists. Parameter names and return types do not determine overloading.

int adjust(int value)
double adjust(double value)
int adjust(int value, int amount)

API and Libraries

  • API: The "instruction manual" for tools — tells you how to call methods
  • Library: A pre-written collection of functionality (e.g., Math, String, Scanner)

Good habit: Read the signature first, then write the call.


12. The Math Class

The Math class provides common mathematical methods:

Math.methodName(arguments)

Common Math Methods for AP CSA

Method SignatureDescriptionExampleResult
int abs(int a)Absolute value (int)Math.abs(-13)13
double abs(double a)Absolute value (double)Math.abs(-4.5)4.5
double pow(double a, double b)a to the power of bMath.pow(2, 4)16.0
double sqrt(double a)Square rootMath.sqrt(144)12.0
double random()Random number [0.0, 1.0)Math.random()0.0 ~ 0.999...

Math Methods in Expressions

double result = Math.sqrt(Math.pow(3, 2));  // 3.0
double value = Math.abs(-4.5) + 1.5;        // 6.0
double power = Math.pow(5, 0);              // 1.0
double power = Math.pow(-3, 2);             // 9.0

13. Random Number Generation

Three-Step Method for Integer Ranges

Math.random() returns a random double in [0.0, 1.0).

To generate integers in a specific range, follow three steps:

int dice = (int) (Math.random() * 6) + 1;   // 1 ~ 6

Step-by-step breakdown:

Math.random()                   → [0.0, 1.0)
* 6                             → [0.0, 6.0)
(int) ...                       → {0, 1, 2, 3, 4, 5}
+ 1                             → {1, 2, 3, 4, 5, 6}

General Formula

int result = (int) (Math.random() * rangeSize) + offset;
CodeResult Range
(int)(Math.random() * 8) + 22 ~ 9
(int)(Math.random() * 10) + 1010 ~ 19
(int)(Math.random() * 5)0 ~ 4
(int)(Math.random() * 7) + 11 ~ 7
(int)(Math.random() * 100) + 900900 ~ 999

14. Classes and Objects

Core Concepts

ConceptAnalogyDescription
ClassBlueprint for building robotsDefines common attributes (data) and behaviors (methods)
ObjectOne specific robot built from the blueprintOne concrete instance of a class
class  -> blueprint
object -> one concrete instance

Instance Methods vs Class Methods

Call FormatMeaningExample
ClassName.methodName(...)Class method (static)Math.abs(-5)
objectName.methodName(...)Instance method (belongs to object)word.length()

15. Primitive vs Reference

This is one of the most important conceptual distinctions in AP CSA. 🔑

Variable TypeStorageExample
PrimitiveStores the value directlyint score = 100;
ReferenceStores a reference (address) to the objectString name = new String("Ava");
int score = 100;                    // primitive: stores value directly
double average = 92.5;              // primitive: stores value directly
boolean isReady = true;             // primitive: stores value directly
String name = new String("Ava");    // reference: stores a reference to an object

Visual Analogy

  • Primitive: Like a drawer that holds the object directly
  • Reference: Like a map that tells you where to find the object

Common AP question: int a = 5; int b = a; a = 10; — b is still 5, because primitive assignment copies the value.


16. Creating Objects: new and Constructors

Standard Creation

String message = new String("Hello");
Variable nameKeywordConstructor
messagenewString("Hello") (same name as class)

String's Special Case

String can be created without new, using a literal:

String message = "Hello";                // literal (more common)
String message2 = new String("Hello");   // explicit constructor (same result)

17. The String Class

String Indexes

Count actual characters, not source-code symbols. Each of \", \\, and \n represents 1 character. The surrounding quotation marks that delimit the string do not count toward its length.

String text = "A\"B\\C\nD";
System.out.println(text.length()); // 7

The characters are A, ", B, \, C, a newline, and D. The newline occupies one position, so D is at index 6.

Each character in a string has a position number (index), starting at 0:

String word = "coding";
// index: c=0, o=1, d=2, i=3, n=4, g=5
RuleFormula
First character index0
Last character indexlength() - 1

String Concatenation

String first = "Hello";
String name = "Ava";

String greeting = first + name;            // "HelloAva"
String message = first + ", " + name;      // "Hello, Ava"
String label = "Score: " + 42;             // "Score: 42"

String + Number Mixing Rules — AP MUST-KNOW 🔥

System.out.println("Score: " + 4 + 2);    // "Score: 42"
System.out.println(4 + 2 + " points");    // "6 points"

Rule: + runs left to right. Once a String is encountered, everything after it becomes string concatenation.


18. String Instance Methods Quick Reference

Method SignatureDescriptionExampleResult
int length()Returns string length"coding".length()6
String substring(int from, int to)Extracts [from, to)"coding".substring(1, 4)"odi"
String substring(int from)Extracts from to end"coding".substring(2)"ding"
int indexOf(String str)Returns first index of str"banana".indexOf("na")2
boolean equals(Object other)Compares content"java".equals("Java")false
int compareTo(String other)Lexicographic comparison"ant".compareTo("apple")negative
String[] split(String del)Splits by delimiter"a-b-c".split("-")["a","b","c"]

Getting a Single Character

String word = "coding";
String letter = word.substring(2, 3);    // "d"

Formula: str.substring(index, index + 1)

compareTo Rules

"ant".compareTo("apple");   // negative: ant < apple (lexicographically earlier)
"dog".compareTo("cat");     // positive: dog > cat
"dog".compareTo("dog");     // 0: equal

19. Immutability

String objects are immutable. This is an AP CSA MUST-KNOW concept. 🔑

Core Meaning

A String object never changes itself. Any operation that seems to "modify" a String actually returns a new String object.

String word = "coding";

word.substring(0, 3);              // returns "cod", but it's not captured!
System.out.println(word);          // still "coding"

word = word.substring(0, 3);       // captured the return value
System.out.println(word);          // "cod"

Common Mistake

String word = "coding";
word.substring(0, 3);              // ❌ return value not captured, lost
System.out.println(word);          // "coding" (not "cod"!)

Correct Approach

To keep the result of a String method, you must capture the return value:

word = word.toUpperCase();         // ✅ reassign to capture
String result = word.substring(0, 3);  // ✅ store in new variable

20. null vs Empty String

These two concepts are easy to confuse. 🔑

String a = "";       // empty string: a real String object with no content
String b = null;     // null: the variable does not point to any object
StateMeaningCan call methods?
""Empty string object✅ length() returns 0
nullNo object❌ length() throws NullPointerException
String empty = "";
String nickname = null;

System.out.println(empty.length());     // 0 ✅
System.out.println(nickname.length());  // NullPointerException ❌

null is NOT an empty string, NOT 0, and NOT false — it means "there is no object here."


21. Common Pitfalls

🔥 #1: Integer Division

int result = 10 / 4;    // 2 (not 2.5!)

When two ints divide, the result is an int — the decimal part is truncated.

🔥 #2: Cast Precedence

(int) 9.9 * 2     // 18 — cast only applies to 9.9
(int) (9.9 * 2)   // 19 — multiply first, then truncate

🔥 #3: Immutability

String s = "hello";
s.substring(0, 2);      // not captured, result lost
System.out.println(s);  // "hello" (unchanged!)

🔥 #4: String + Number Order

"Score: " + 4 + 2    // "Score: 42" (left to right, String met first)
4 + 2 + " points"    // "6 points" (numeric addition first)

🔥 #5: Assignment Compatibility

double d = 5;     // ✅ int auto-promotes to double
int i = 3.5;      // ❌ compile error
int i = (int)3.5; // ✅ OK with explicit cast

🔥 #6: Overflow

Integer.MAX_VALUE + 1  // becomes Integer.MIN_VALUE (negative!)

🔥 #7: null vs ""

"".length()      // 0 ✅
null.length()    // NullPointerException ❌

🔥 #8: Variable Independence

int a = 5;
int b = a;
a = 10;
// b is still 5, not 10!