Table of Contents

Introduction to Generics in Java

Generics in Java enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. They provide a way to reuse the same code with different data types while ensuring type safety.

Key Concepts of Generics:

1. Generics

Definition:

Generics allow you to define classes, interfaces, and methods with a placeholder for the type they operate on. This placeholder is replaced with a specific type when the code is executed.

Benefits:

Example:

public class Box<T> {
    private T value;

    public void setValue(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public static void main(String[] args) {
        Box<Integer> intBox = new Box<>();
        intBox.setValue(10);
        System.out.println("Integer Value: " + intBox.getValue());

        Box<String> strBox = new Box<>();
        strBox.setValue("Hello");
        System.out.println("String Value: " + strBox.getValue());
    }
}

Output:

Integer Value: 10
String Value: Hello

2. Type Safety

Definition:

Type safety ensures that a variable is only assigned values of a specific type. Generics provide compile-time type checking, which helps catch errors early in the development process.

Example:

Without generics, you might use Object to hold different types, which requires casting and can lead to runtime errors: