01 / 21
<T>

Type Parameters &
Type Checking

Learn how Java uses generics and compile-time type checking to write safer, reusable code that catches errors before your program ever runs.

AP Computer Science A

What Is a Type in Java?

Every variable in Java has a type that tells the compiler what kind of data it holds and what operations are allowed. Types are checked at compile time: if something doesn't match, your code won't even compile.

Primitive
Built-in types like int, double, boolean: fixed-size, stack-allocated values.
Reference
Objects and arrays like String, ArrayList: stored on the heap, accessed through a reference.

The Problem Without Generics

Before Java 5, collections stored everything as Object. You could put any type in, but when you took something out, you had to cast it: risky and error-prone.

ArrayList list = new ArrayList(); // raw type list.add("hello"); list.add(42); // no compile error! String s = (String) list.get(1); // ClassCastException at RUNTIME

Introducing Type Parameters

A type parameter (or generic) is a placeholder for a type. You declare it in angle brackets <T> and fill it in when you use the class or method. This lets one class work safely with many types.

ArrayList<String> words = new ArrayList<String>(); words.add("hello"); // ✓ allowed words.add(42); // ✕ compile error! String s = words.get(0); // no cast needed

How Compile-Time Checking Works

Source Code ArrayList<String> Compiler Checks every type usage ✓ Compiles Type-safe bytecode ✕ Error Type mismatch ✓ words.add("hi") ✕ words.add(42) ✓ String s = words.get(0)

The Core Rule of Generics

public class Box<T> { private T item; public void set(T item) { this.item = item; } public T get() { return item; } } Box<Integer> intBox = new Box<Integer>(); intBox.set(7); // T is now Integer Integer n = intBox.get(); // returns Integer, no cast

T is not a real type: it's a placeholder the compiler fills in. After compilation, the bytecode uses Object internally (this is called type erasure).

Anatomy of a Generic Class

public class Pair <A, B> { Type parameters private A first; private B second; public Pair ( A a, B b) { ... } public A getFirst () { ... } public B getSecond () { ... } } Return types match the type parameters

Generics vs Raw Types

Generic (ArrayList<String>) Raw (ArrayList)
Type safety Compile-time None
Casting needed? No Yes, manual
Wrong-type add Compile error Silently allowed
ClassCastException? Prevented Possible at runtime
Code readability Self-documenting Ambiguous

How to Apply Type Parameters

1
Declare the type parameter. Place it in angle brackets after the class or method name: class Box<T>.
2
Use T as a type. Replace concrete types in fields, parameters, and return types with T.
3
Specify the argument. When creating an instance, supply the actual type: Box<String>.
4
Let the compiler verify. It checks every usage. If you try to pass an incompatible type, you get a compile error.
5
No casting required. When you retrieve values, the compiler already knows the type: clean, safe code.

Example 1: ArrayList<String>

ArrayList<String> names = new ArrayList<String>(); names.add("Alice"); names.add("Bob"); // The compiler knows get() returns String String first = names.get(0); System.out.println(first.toUpperCase()); // "ALICE" // names.add(100); ← compile error: int ≠ String

Example 2: Custom Generic Class

public class Wrapper<T> { private T value; public Wrapper(T value) { this.value = value; } public T getValue() { return value; } }
// Usage with different types: Wrapper<Integer> w1 = new Wrapper<Integer>(42); Integer num = w1.getValue(); // ✓ returns Integer Wrapper<Boolean> w2 = new Wrapper<Boolean>(true); Boolean flag = w2.getValue(); // ✓ returns Boolean // w1.getValue().toUpperCase(); ← compile error! // Integer has no toUpperCase method

Example 3: Type Errors Caught Early

Here's what happens when you try to violate the type contract. The compiler catches every mistake before you can run the code:

ArrayList<Double> scores = new ArrayList<Double>(); scores.add(95.5); scores.add(87.0); // ERROR 1: wrong type added scores.add("A+"); // ✕ String cannot be added to ArrayList<Double> // ERROR 2: wrong variable type String s = scores.get(0); // ✕ Double cannot be assigned to String // CORRECT: Double d = scores.get(0); // ✓ returns Double

Under the Hood: Type Erasure

Your Code (Source) Box<String> b; String s = b.get(); javac Bytecode (Runtime) Box b; String s = (String)b.get(); Type erasure removes generic info at compile time. The compiler inserts casts automatically: safe because it already verified all types are correct.

Primitives Need Wrapper Classes

Type parameters only work with reference types, not primitives. Java provides wrapper classes that box primitives into objects. Autoboxing handles the conversion automatically.

Primitive Wrapper Class Generic Usage
int Integer ArrayList<Integer>
double Double ArrayList<Double>
boolean Boolean ArrayList<Boolean>

Common Mistakes with Generics

✕ Using Primitives
Writing ArrayList<int> instead of ArrayList<Integer>. Type parameters require reference types.
✕ Using Raw Types
Omitting the type argument: ArrayList list compiles but loses all type safety checks.
✕ Ignoring Compiler Warnings
"Unchecked" warnings mean the compiler can't verify types. They often signal a raw type lurking in your code.

Summary: Key Concepts

Concept What It Means Why It Matters
Type Parameter Placeholder type: <T>, <E>, <K,V> Enables reusable, type-safe code
Type Argument Actual type supplied: <String> Locks a specific usage to one type
Compile-time Checking Compiler verifies all types match Catches bugs before runtime
Type Erasure Generics removed in bytecode No runtime overhead; explains limits
Autoboxing int ↔ Integer automatically Lets primitives work with generics

Question 1 of 5

What is the primary purpose of type parameters (generics) in Java?

Question 2 of 5

Which of the following will cause a compile-time error?

Question 3 of 5

Why can't you write ArrayList<int> in Java?

Question 4 of 5

Consider the generic class below. What does the compiler guarantee about w.getValue()?

Question 5 of 5

What happens to generic type information at runtime in Java?