Using Objects and Methods

The foundation: how Java represents data with primitive types, how programs are built from classes and objects, and how to use methods to make objects do things.

1.1 Primitive Types

A primitive type is a built-in data type — a piece of value stored directly in a variable. AP CSA tests exactly three:

TypeHoldsExampleRange
intWhole numberint age = 17;≈ ±2.1 billion
doubleDecimal numberdouble gpa = 3.85;very large
booleantrue or falseboolean done = true;2 values
📘 Only these three

Java has other primitives (char, long, float) but the AP CSA exam only tests int, double, and boolean.

Declaration and initialization

int score;          // declare — reserve storage
score = 95;         // assign — put a value in
int level = 1;      // declare and assign in one line

Naming rules

  • Start with a letter, $, or _ — never a digit
  • Case-sensitive: Score and score are different variables
  • Cannot be a Java reserved word
  • Convention: camelCase for variables, PascalCase for classes
✏️ Your turn

Inside main, declare three variables and print them:

  • an int called age set to your age
  • a double called gpa set to a GPA like 3.85
  • a boolean called isStudent set to true

Print each on its own line in the form Age: 17, GPA: 3.85, Student? true.

Show solution
public class Main {
    public static void main(String[] args) {
        int age = 17;
        double gpa = 3.85;
        boolean isStudent = true;

        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);
        System.out.println("Student? " + isStudent);
    }
}

1.2 Expressions and Assignment

An expression evaluates to a value. Arithmetic in Java uses these operators:

OperatorMeaningExampleResult
+Add5 + 38
-Subtract5 - 32
*Multiply5 * 315
/Divide10 / 42 (int division)
%Mod (remainder)10 % 31
🚨 The #1 trap: Integer Division

When both operands are int, division truncates. 7 / 2 is 3, not 3.5. To get the decimal, at least one operand must be a double: 7.0 / 2 gives 3.5.

Compound assignment operators

ShortcutEquivalent to
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = x / 2
x %= 2x = x % 2
x++ / ++xx = x + 1
x-- / --xx = x - 1
📘 Pre vs post — not tested

AP CSA does not test the difference between ++x and x++. Treat them as the same.

The mod operator % is your friend

  • n % 2 == 0n is even
  • n % 10 → last digit of n
  • n / 10 → drops the last digit
✏️ Your turn — operators & mod

Print each of these on its own line, in order:

  1. 7 / 2 (watch integer division)
  2. 7 % 2
  3. 7.0 / 2
  4. 2 + 3 * 4
  5. (2 + 3) * 4

Then declare int count = 10;, apply += 5, then *= 2, then %= 7, and print count: followed by the result.

Expected output: 3, 1, 3.5, 14, 20, count: 2

Show solution
public class Main {
    public static void main(String[] args) {
        System.out.println(7 / 2);          // 3
        System.out.println(7 % 2);          // 1
        System.out.println(7.0 / 2);        // 3.5
        System.out.println(2 + 3 * 4);      // 14
        System.out.println((2 + 3) * 4);    // 20

        int count = 10;
        count += 5;   // 15
        count *= 2;   // 30
        count %= 7;   // 2
        System.out.println("count: " + count);
    }
}
What does System.out.println(17 % 5); print?
A 3
B 2
C 3.4
D 5

1.3 Casting and Ranges

Casting converts a value from one type to another.

Implicit widening (automatic)

Java auto-converts intdouble because every int fits in a double safely.

int n = 5;
double d = n;    // automatic: 5.0

Explicit narrowing (you write the cast)

To go doubleint, you must write (int). This truncates — drops the decimal, doesn't round.

🚨 Cast truncates, doesn't round

(int) 9.99 is 9, not 10. To round: (int) Math.round(x) or (int)(x + 0.5) for positives.

Forcing real division

This is the most common AP exam use of casting:

✏️ Your turn — casting

Declare int a = 7, b = 2; and print, in order:

  1. a / b as-is
  2. the same division but cast a to double before dividing
  3. cast b instead
  4. cast the whole thing after dividing (you'll see the trap)

Then with double d = 4.99;, print (int) d (truncates) and a version that rounds by adding 0.5 before casting.

Expected: 3, 3.5, 3.5, 3.0, 4, 5

Show solution
public class Main {
    public static void main(String[] args) {
        int a = 7, b = 2;

        System.out.println(a / b);            // 3
        System.out.println((double) a / b);   // 3.5
        System.out.println(a / (double) b);   // 3.5
        System.out.println((double)(a / b));  // 3.0 — cast too late

        double d = 4.99;
        System.out.println((int) d);          // 4 truncated
        System.out.println((int)(d + 0.5));   // 5 rounded
    }
}

Range of int and overflow

int ranges from Integer.MIN_VALUE (–2,147,483,648) to Integer.MAX_VALUE (2,147,483,647). Past the max, the value wraps around to the negative end. No exception — just wrong answer.

✏️ Your turn — overflow

Print Integer.MAX_VALUE, then Integer.MAX_VALUE + 1 (you'll see overflow wrap around), then Integer.MIN_VALUE. Confirm the second matches the third.

Show solution
public class Main {
    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);       // 2147483647
        System.out.println(Integer.MAX_VALUE + 1);   // -2147483648
        System.out.println(Integer.MIN_VALUE);       // -2147483648
    }
}
What is the value of (double)(13 / 5)?
A 2.6
B 2.0
C 2
D Compile error

1.4 Objects and Classes

A class is a blueprint. An object is a specific thing built from that blueprint. String is a class; "hello" is one specific String object (also called an instance).

Think of Dog as a class — the cookie cutter. The cookies you cut out are instances. Each can have its own name and age, but they all share the shape.

Key vocabulary

  • Class — the type/blueprint (String, Math, Dog)
  • Object / instance — a specific value of that type in memory
  • Field / attribute / instance variable — data the object holds
  • Method — an action the object can perform
  • Reference — the variable that points to the object
📘 References, not values

When you write String s = "hi";, the variable s stores a reference to a String object in memory — not the characters themselves. This matters for comparison (Unit 2) and parameter passing (Unit 3).

1.5 Creating Objects with new

To build an object you use new followed by a constructor (a method named after the class):

ClassName variableName = new ClassName(arguments);
✏️ Your turn — three ways to make an object

Create and print three objects:

  1. a String called greeting built with the explicit new String(...) constructor, holding "Hello"
  2. a String called name built with the literal shortcut (no new), holding your name
  3. an Integer called score built with Integer.valueOf(95)

Print each one.

Show solution
public class Main {
    public static void main(String[] args) {
        String greeting = new String("Hello");
        System.out.println(greeting);

        String name = "Anita";
        System.out.println(name);

        Integer score = Integer.valueOf(95);
        System.out.println(score);
    }
}

The null reference

A reference can hold null — pointing at no object. Calling a method on null throws NullPointerException.

String s = null;
System.out.println(s.length());  // 💥 NullPointerException

1.6 Calling Methods

You call methods with dot notation: object.methodName(args). Methods come in two flavors:

void methods — do something, return nothing

✏️ Your turn — print vs println

Using only System.out.print and System.out.println, produce this exact output:

void method

no newline ...now newline.

Hint: println() with no argument prints a blank line. print doesn't add a newline.

Show solution
public class Main {
    public static void main(String[] args) {
        System.out.println("void method");
        System.out.println();              // blank line
        System.out.print("no newline");
        System.out.println(" ...now newline.");
    }
}

Non-void methods — return a value

You should usually do something with the return value: store it, print it, or use it in an expression.

✏️ Your turn — use the return value

Given String word = "Spaghetti";:

  1. Store the result of word.length() in an int called len and print length = 9
  2. Print word.toUpperCase() directly (don't store it first)
Show solution
public class Main {
    public static void main(String[] args) {
        String word = "Spaghetti";

        int len = word.length();
        System.out.println("length = " + len);

        System.out.println(word.toUpperCase());
    }
}
⚠ Strings are immutable

word.toUpperCase() doesn't change word — it returns a new String. If you don't assign the result, it's thrown away.

Parameters vs. arguments

Parameters are the variables in the method's declaration. Arguments are the actual values you pass when you call it. Java matches them by position.

1.7 String Objects and Concatenation

Strings are objects, but Java gives them special syntax: quotes for literals, + for concatenation.

The + operator

  • Both sides numbers → arithmetic addition
  • Either side a String → convert the other and join them
  • Evaluated left to right
✏️ Your turn — concatenation & escapes

Print these four expressions and predict the output before running:

  1. "Score: " + 5 + 10
  2. "Score: " + (5 + 10)
  3. 5 + 10 + " total"
  4. "A" + "B" + "C"

Then write four printlns using escape sequences to produce:

  • The text She said "hi" (with real double-quotes)
  • Two lines: line1 then line2, from one string using \n
  • tab, a tab, then here
  • a\b (a literal backslash)
Show solution
public class Main {
    public static void main(String[] args) {
        System.out.println("Score: " + 5 + 10);   // Score: 510
        System.out.println("Score: " + (5 + 10)); // Score: 15
        System.out.println(5 + 10 + " total");    // 15 total
        System.out.println("A" + "B" + "C");      // ABC

        System.out.println("She said \"hi\"");
        System.out.println("line1\nline2");
        System.out.println("tab\there");
        System.out.println("a\\b");
    }
}
🚨 Left-to-right trap

"" + 3 + 4 evaluates as "" + 3 = "3", then "3" + 4 = "34". Watch for this on the exam.

1.8 String Methods

Memorize these. They appear constantly on the AP exam.

MethodReturnsExample
length()int"hello".length() → 5
substring(i, j)String, index i to j-1"hello".substring(1, 4) → "ell"
substring(i)String, i to end"hello".substring(2) → "llo"
indexOf(s)first index of s, or -1"hello".indexOf("l") → 2
equals(s)boolean — same chars?"hi".equals("hi") → true
compareTo(s)negative / 0 / positive"apple".compareTo("banana") → negative
🚨 Strings are 0-indexed

First char is at index 0. Last is at length() - 1. Index length() itself is out of bounds and throws StringIndexOutOfBoundsException.

✏️ Your turn — String methods

With String s = "Computer Science";, print, in order:

  1. its length, labeled length:
  2. the first 8 characters (substring 0 to 8), labeled 0-8:
  3. everything from index 9 on, labeled 9+:
  4. the index of "S", labeled indexOf 'S':
  5. the index of "z" (you'll get -1), labeled indexOf 'z':

Then with String a = "hello", b = "hello";, print a.equals(b) and a.compareTo("help").

Show solution
public class Main {
    public static void main(String[] args) {
        String s = "Computer Science";
        System.out.println("length: " + s.length());
        System.out.println("0-8: " + s.substring(0, 8));
        System.out.println("9+: " + s.substring(9));
        System.out.println("indexOf 'S': " + s.indexOf("S"));
        System.out.println("indexOf 'z': " + s.indexOf("z"));

        String a = "hello", b = "hello";
        System.out.println(a.equals(b));
        System.out.println(a.compareTo("help"));
    }
}
⚠ Use .equals(), NOT ==

For Strings, == compares references — whether they're the same object — not characters. Always use .equals() for content comparison.

What does "AP Computer".substring(3, 8) return?
A "Comput"
B "Compu"
C "Comp"
D Exception

1.9 The Math Class & Using Libraries

The Math class is a library of static methods — call them on the class, not on an instance.

MethodReturnsExample
Math.abs(x)absolute valueMath.abs(-5) → 5
Math.pow(b, e)be as doubleMath.pow(2, 10) → 1024.0
Math.sqrt(x)√x as doubleMath.sqrt(16) → 4.0
Math.random()double in [0.0, 1.0)Math.random() → 0.7361…
💡 Random integer in [a, b]

Formula: (int)(Math.random() * (b - a + 1)) + a — memorize this, it's on the exam.

✏️ Your turn — Math class

Print:

  1. Math.abs(-7)
  2. Math.pow(2, 8)
  3. Math.sqrt(144)
  4. A random die roll (integer 1 to 6 inclusive), labeled Die:
  5. A random integer 10 to 20 inclusive, labeled [10,20]:

Use the formula (int)(Math.random() * (b - a + 1)) + a for ranges.

Show solution
public class Main {
    public static void main(String[] args) {
        System.out.println(Math.abs(-7));
        System.out.println(Math.pow(2, 8));
        System.out.println(Math.sqrt(144));

        int roll = (int)(Math.random() * 6) + 1;
        System.out.println("Die: " + roll);

        int x = (int)(Math.random() * 11) + 10;
        System.out.println("[10,20]: " + x);
    }
}

Wrapper classes: Integer and Double

Primitives aren't objects. Wrapper classes let you treat them as objects (needed for ArrayList in Unit 4).

  • intInteger
  • doubleDouble

Java auto-converts between them (autoboxing/unboxing).

✏️ Your turn — wrappers & parsing

Write code that:

  1. Stores 42 in an Integer called boxed (autoboxing)
  2. Computes boxed + 8 into an int called unboxed and prints it
  3. Prints Integer.MAX_VALUE
  4. Parses "123" with Integer.parseInt, adds 1, and prints (should print 124)
  5. Parses "3.14" with Double.parseDouble and prints it
Show solution
public class Main {
    public static void main(String[] args) {
        Integer boxed = 42;
        int unboxed = boxed + 8;
        System.out.println(unboxed);

        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.parseInt("123") + 1);
        System.out.println(Double.parseDouble("3.14"));
    }
}
Which expression generates a random integer 1 to 100 inclusive?
A (int)(Math.random() * 100)
B (int)(Math.random() * 100) + 1
C (int)(Math.random() * 101) + 1
D (int)(Math.random() * 99) + 1

🎯 Unit 1 Review Quiz

1. What is printed by System.out.println("Hi" + 3 + 4);?
A Hi34
B Hi7
C 7Hi
D Compile error
2. After int x = 10; x += 3; x *= 2; what is x?
A 16
B 23
C 26
D 60
3. Why use .equals() instead of == for Strings?
A Because == doesn't compile
B == compares references, not characters
C Speed
D == throws an exception