What are generics in Java?

Generics in Java allow classes, interfaces, and methods to operate on different data types while maintaining type safety. They enable developers to write reusable and type-safe code without explicit type casting.

Key Points: • Generics provide compile-time type checking, reducing runtime errors. • They improve code reusability by allowing a single class or method to work with multiple data types. • Generics eliminate the need for explicit type casting when retrieving objects. • They are widely used in the Collections Framework, such as List<String> and Map<Integer, String>. • Generic types make code more readable, maintainable, and less error-prone.

Example: An ArrayList<String> can store only String objects, preventing accidental insertion of other data types and catching errors during compilation.

Code Example:

import java.util.ArrayList;
import java.util.List;

public class Demo {

    public static void main(String[] args) {

        List<String> names = new ArrayList<>();

        names.add("Java");

        String name = names.get(0);

        System.out.println(name);
    }
}

Interview Tip: A concise interview answer is:

"Generics allow us to create type-safe and reusable classes, interfaces, and methods. They provide compile-time type checking, reduce runtime errors, eliminate explicit type casting, and are extensively used in the Java Collections Framework."