Java Generics Example in Java
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
KOTLINBest Practices
Common Mistakes
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:
class Box<T> {— performs part of the program’s logic.private T value;— performs part of the program’s logic.public void set(T value) { this.value = value; }— declares or assigns a value the program uses.public T get() { return value; }— performs part of the program’s logic.public String toString() {— defines a function used by the program.return "Box holds: " + value + " (" + value.getClass().getSimpleName() + ")";— returns the computed result.public class GenericsDemo {— performs part of the program’s logic.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.