Skip to lesson

Generics let a class or method say which type of value it works with: Box<String>, Box<Integer>, ArrayList<String>. The Java compiler (javac) then checks every value that goes in and comes out, so a type mistake is caught before the program runs instead of crashing it later.

The old way: Object and casts

Type safety means the compiler makes sure every variable and object only ever gets values of the right type. A type mistake is then caught while the program is compiled, not when a customer is using the app.

An online store needs a small holder for one value: a product name, a price, an order number. One Object field can hold all of them, because every class is a child of Object (opens in a new tab).

Example 1 · An Object box: casts, and a crash

ObjectBoxDemo.javaJava
class ObjectBox {    private Object value;
    void set(Object value) {        this.value = value;    }
    Object get() {        return value;    }}
public class ObjectBoxDemo {    static void saveOrderNumber(ObjectBox box) {        box.set("A17");    }
    public static void main(String[] args) {        ObjectBox productBox = new ObjectBox();        productBox.set("Laptop");        String product = (String) productBox.get();        System.out.println("Product: " + product + " (" + product.length() + " letters)");
        ObjectBox orderBox = new ObjectBox();        saveOrderNumber(orderBox);        Integer order = (Integer) orderBox.get();        System.out.println("Next order: " + (order + 1));    }}
Sample output (the program stops with an exception)
Product: Laptop (6 letters)
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at ObjectBoxDemo.main(ObjectBoxDemo.java:26)

What this code does

  • ObjectBox stores an Object, so the same class holds any value. get() returns Object, so every read needs a cast such as (String); without it, product.length() does not compile.
  • The first cast is right, so Product: Laptop (6 letters) prints.
  • The program compiles with no error, but saveOrderNumber stored the text "A17". The cast to Integer fails only when that line runs: a ClassCastException, far from the real bug.

A cast is a promise to the Java compiler: "trust me, this is an Integer". The compiler cannot check that promise. As in Downcasting (opens in a new tab), the JVM checks it only when that line runs, so a broken promise becomes a crash.

A compile error costs you a minute at your desk. A crash in a running app costs a customer their order.

Generics: the type becomes a parameter

Generics are a Java feature that lets a class, interface or method take a type as a parameter, like Box<T>. You fill in the type when you use it (Box<String>), and the compiler checks every value against it, so no casts are needed.

Give the box a placeholder T for the type, and let each user of the class choose it. One class then serves as a Box<String> for product names and a Box<Integer> for prices, each one checked by the Java compiler.

Example 2 · The same box with generics

GenericBoxDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class GenericBoxDemo {    public static void main(String[] args) {        Box<String> productBox = new Box<>();        productBox.set("Laptop");        String product = productBox.get();        System.out.println("Product: " + product.toUpperCase());
        Box<Integer> priceBox = new Box<>();        priceBox.set(60000);        int price = priceBox.get();        System.out.println("Price with 5% GST: Rs. " + (price + price * 5 / 100));    }}
Output
Product: LAPTOP
Price with 5% GST: Rs. 63000

What this code does

  • class Box<T> is written once and used twice: as Box<String> and as Box<Integer>.
  • In a Box<String>, get() returns a String, so product.toUpperCase() works with no cast.
  • priceBox.set(60000) and int price = priceBox.get() convert between int and Integer by themselves; Write a generic class (opens in a new tab) calls this autoboxing.

Example 3 · The compiler catches the mistake

OrderCheckDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class OrderCheckDemo {    static void saveOrderNumber(Box<Integer> box) {        box.set("A17");    }
    public static void main(String[] args) {        Box<Integer> orderBox = new Box<>();        saveOrderNumber(orderBox);        System.out.println("Order " + orderBox.get());    }}
Sample compiler output
OrderCheckDemo.java:15: error: incompatible types: String cannot be converted to Integer
        box.set("A17");
                ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

What this code does

  • This is the bug from Example 1, but the parameter is now a Box<Integer>.
  • The compiler refuses the wrong line and points right at it, inside saveOrderNumber, where the mistake really is.
  • The fix is box.set(17);. A program with this bug can never be built, so no customer ever sees it.

The bug from the first section, now with a Box<Integer>, never reaches a customer. That is the whole point of generics: the type check moves from run time, when the customer waits, to compile time, when you are still at your desk.

Type parameter and type argument

A type parameter is the placeholder in a generic declaration, like T in class Box<T>. A type argument is the real type you put in its place when you use the class, like Product in Box<Product>.

A method parameter is a placeholder for a value; a type parameter is a placeholder for a type. Below, Product is the type argument, so get() hands back a Product whose fields are ready to use.

Example 4 · A box of your own objects

DealDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
class Product {    String name;    int price;
    Product(String name, int price) {        this.name = name;        this.price = price;    }}
public class DealDemo {    public static void main(String[] args) {        Box<Product> deal = new Box<>();        deal.set(new Product("Monitor", 11000));        System.out.println("Deal of the day: " + deal.get().name + ", Rs. " + deal.get().price);
        Product offer = new Product("Webcam", 2500);        if (offer.price < deal.get().price) {            deal.set(offer);        }        System.out.println("Deal of the day: " + deal.get().name + ", Rs. " + deal.get().price);    }}
Output
Deal of the day: Monitor, Rs. 11000
Deal of the day: Webcam, Rs. 2500

What this code does

  • Box<Product> fills the type parameter T with the type argument Product.
  • So deal.get() returns a Product, and deal.get().price works directly. With an ObjectBox you would write ((Product) deal.get()).price every time.
  • deal.set(offer) compiles because offer is a Product; deal.set("Webcam") would not.

The class is written once with T. Each variable then fixes T for itself: Box<String>, Box<Integer> and Box<Product> are three uses of one class. Write a generic class (opens in a new tab) shows how to declare your own.

The diamond operator <>

The diamond operator <> is the empty pair of angle brackets in new Box<>(). It tells the compiler to work out the type argument from the left side of the line, so you write Box<String> b = new Box<>(); instead of repeating String.

Writing the type on both sides is noise: Box<String> b = new Box<String>();. Since Java 7, the empty <> lets the Java compiler copy it from the left.

Java
Box<String> a = new Box<String>();   // works, but repeats StringBox<String> b = new Box<>();         // the compiler fills in StringBox<Product> c = new Box<>();        // the compiler fills in Product

All three lines create a correctly typed box; the last two are the normal modern style. The diamond is not the same as leaving the brackets out: new Box() with no <> at all creates a raw type, the topic of the next section.

Raw types: generics switched off

A raw type is a generic class used without any type argument, like ArrayList instead of ArrayList<String>. The compiler then switches off its type checks for that variable and gives only a warning, so wrong values get in and crash later.

ArrayList is Java's own growing list (ArrayList basics (opens in a new tab)); here you need only add and get. Below, the same order list is written twice: first raw, then as an ArrayList<String>.

Left: a raw ArrayList takes anything, so "Laptop", 5 and "Keyboard" all go in, and reading 5 as a String crashes with a ClassCastException at run time. Right: an ArrayList<String> accepts only Strings: "Mouse" goes in, 5 is stopped by the compiler with an error.

Example 5 · A raw list compiles, then crashes

RawOrders.javaJava
import java.util.ArrayList;
public class RawOrders {    public static void main(String[] args) {        ArrayList orders = new ArrayList();        orders.add("Laptop");        orders.add(5);        String second = (String) orders.get(1);        System.out.println(second);    }}
Sample output (the program stops with an exception)
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
	at RawOrders.main(RawOrders.java:8)

What this code does

  • The raw ArrayList holds plain Object values, so the product name and the number 5 both go in.
  • The compiler cannot check a raw list, so it only prints a warning ("uses unchecked or unsafe operations") and the program is built, bug included.
  • The cast on line 8 is checked only when it runs. The object is an Integer, not a String, so the program crashes.

Example 6 · ArrayList<String>: the compiler stops it

TypedOrders.javaJava
import java.util.ArrayList;
public class TypedOrders {    public static void main(String[] args) {        ArrayList<String> orders = new ArrayList<>();        orders.add("Laptop");        orders.add(5);        String second = orders.get(1);        System.out.println(second);    }}
Sample compiler output
TypedOrders.java:7: error: incompatible types: int cannot be converted to String
        orders.add(5);
                   ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

What this code does

  • The same list with the type argument String. Now the compiler knows every element must be a String.
  • orders.add(5) is refused at compile time, with the exact line number. No program is built until that line is fixed.
  • orders.get(1) needs no cast: an ArrayList<String> hands back a String.

Code written before Java 5 (2004) has no type arguments, and Java still accepts it, so you will meet raw types in old projects. In your own code, always give a type argument. If the compiler prints "uses unchecked or unsafe operations", a raw type is hiding somewhere.

Next step

Check your understanding

12 quick questions