Skip to main content

Java Generics Example in Java

2 min read Updated May 29, 2026
Share:
On this page (7sections)

Introduction

Generics let you write classes, interfaces and methods that operate on types specified by the caller. They eliminate unsafe casts and make collection code clearer.

Example Program

import java.util.*;

class Box<T> {
    private T value;

    public void set(T value) { this.value = value; }
    public T get() { return value; }

    @Override
    public String toString() {
        return "Box holds: " + value + " (" + value.getClass().getSimpleName() + ")";
    }
}

public class GenericsDemo {
    public static void main(String[] args) {
        Box<String> message = new Box<>();
        message.set("Hello Generics");
        System.out.println(message);

        Box<Integer> number = new Box<>();
        number.set(42);
        System.out.println(number);

        List<String> languages = new ArrayList<>();
        languages.add("Java");
        languages.add("Kotlin");
        // languages.add(10); // Compile error — type-safe

        for (String lang : languages) {
            System.out.println(lang.toUpperCase());
        }
    }
}

Sample Output

Box holds: Hello Generics (String)
Box holds: 42 (Integer)
JAVA
KOTLIN

Best Practices

  • Always specify generic types on collections (List<String>, not raw List).
  • Use bounded wildcards (? extends Number) when writing flexible APIs.
  • Prefer generic methods when the type parameter is independent of the class.

Common Mistakes

  • Using raw types and casting elements manually.
  • Creating arrays of generic types directly (new T[10] is not allowed).

How It Works

Here is a step-by-step walkthrough of how the Java program for Java Generics Example in Java runs, line by line:

  1. class Box<T> { — performs part of the program’s logic.
  2. private T value; — performs part of the program’s logic.
  3. public void set(T value) { this.value = value; } — declares or assigns a value the program uses.
  4. public T get() { return value; } — performs part of the program’s logic.
  5. public String toString() { — defines a function used by the program.
  6. return "Box holds: " + value + " (" + value.getClass().getSimpleName() + ")"; — returns the computed result.
  7. public class GenericsDemo { — performs part of the program’s logic.
  8. public static void main(String[] args) { — defines a function used by the program.

After running it, compare your console output with the Sample Output above. Try changing the values and re-running the program to see how the result changes — experimenting is the fastest way to understand the logic.

Frequently Asked Questions

Why use generics instead of Object?
Generics provide compile-time type checking. You avoid ClassCastException at runtime because the compiler verifies that you store and retrieve the correct type.
Can primitives be used with generics?
No. Use wrapper classes such as Integer, Double and Boolean, or autoboxing converts between primitive and wrapper automatically.

Related Tutorials

Search tutorials