SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
1. Introduction
When I first started learning Java, I wrote code where I had to manually cast objects from
collections and always stay careful that no wrong type slips in at runtime. It was not just
inconvenient — it was actually a source of bugs that only showed up when the program was
already running. That is exactly where Generics come into the picture.
Generics were introduced in Java 5 (also called Java 1.5) back in 2004, and since then they
have completely changed how we write type-safe, reusable code. In simple terms, Generics
allow a class, interface, or method to operate on objects of various types while providing
compile-time type safety. Instead of writing separate logic for integers, strings, and other data
types, you write one generic version and the Java compiler takes care of the rest.
This report is based on my self-learning from video resources on the topic of Generics in Java.
Through this activity, I explored what Generics are, why they were needed, how they work
internally, and where they are practically used in real Java development.
2. What are Generics in Java?
Generics in Java is a feature that enables types (classes and interfaces) to be parameters when
defining classes, interfaces, and methods. Just like how a method accepts parameters to reuse
logic for different values, Generics allow us to reuse the same code for different data types —
but with the guarantee that the type is checked at compile time, not at runtime.
Before Generics were introduced, Java developers used the Object class as a workaround to
write code that could work with any type. However, this approach had a serious drawback —
there was no compile-time type check, and the developer had to explicitly cast the object to the
required type. A wrong cast would throw a ClassCastException at runtime, which is one of the
most common and frustrating bugs in older Java code.
With Generics, these issues are resolved completely. The compiler knows exactly what type is
being stored or returned, so incorrect types are caught before the program even runs. This
makes the code not only safer but also cleaner, since there is no need for manual type casting.
2.1 Basic Syntax of Generics
A generic class is defined using a type parameter placed inside angle brackets (<>). The most
commonly used type parameter names are:
• T — stands for Type (general purpose)
• E — stands for Element (used in collections like List, Set)
• K — stands for Key (used in Map)
• V — stands for Value (used in Map)
• N — stands for Number
1
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
A simple example of a generic class:
class Box<T> {
private T value;
public void setValue(T value) {
[Link] = value;
}
public T getValue() {
return value;
}
}
In this example, T is a placeholder for the actual type that will be provided when an object of
Box is created. So Box<Integer> means T is replaced by Integer, and Box<String> means T is
replaced by String. This way, the same Box class works for any type.
3. Why were Generics Needed?
To truly appreciate Generics, it helps to look at how things were done before they existed. Let
us consider a simple example of an ArrayList before Generics:
// Before Generics (Java 1.4 and earlier)
ArrayList list = new ArrayList();
[Link]("Hello");
[Link](42); // No error at compile time!
String s = (String) [Link](1); // Runtime error: ClassCastException
The above code compiled fine but crashed at runtime because an integer was cast to a String.
There was no way for the compiler to warn the developer about this mistake.
Now, with Generics:
// With Generics (Java 5 onwards)
ArrayList<String> list = new ArrayList<>();
[Link]("Hello");
[Link](42); // Compile-time ERROR! Cannot add int to
ArrayList<String>
The compiler immediately flags the problem. This is the biggest advantage of Generics — errors
are caught at compile time instead of runtime. The three main reasons why Generics were
introduced are:
2
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
• Type Safety: The compiler ensures only the correct type of data can be used,
preventing accidental type mismatches.
• Elimination of Explicit Casting: Without Generics, developers had to cast every
retrieved object. With Generics, the casting is done automatically and safely by the
compiler.
• Code Reusability: One generic class or method can serve multiple data types, reducing
code duplication and improving maintainability.
4. Types of Generics in Java
4.1 Generic Classes
A generic class is a class that is parameterized over types. It allows the class to work with any
object type while maintaining type safety. We already saw the Box<T> example above. Another
common example is a generic Pair class that can hold two values of any type:
class Pair<A, B> {
A first;
B second;
Pair(A first, B second) {
[Link] = first;
[Link] = second;
}
}
// Usage: Pair<String, Integer> p = new Pair<>("Age", 21);
4.2 Generic Methods
A generic method is a method that introduces its own type parameters, independent of the class.
This is useful when only one specific method inside a class needs to work with a generic type.
The type parameter is declared before the return type of the method:
public <T> void printArray(T[] arr) {
for (T element : arr) {
[Link](element + " ");
}
}
This single method can print an array of integers, strings, floats, or any other type. There is no
need to write separate printIntArray, printStringArray methods, and so on.
4.3 Generic Interfaces
3
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
Just like classes, interfaces can also be made generic. The Java Collections Framework makes
heavy use of generic interfaces such as List<E>, Set<E>, Map<K,V>, and Comparable<T>.
Here is an example of a custom generic interface:
interface Container<T> {
void add(T item);
T get(int index);
}
4.4 Bounded Type Parameters
Sometimes we want to restrict the types that can be used as type arguments. For example, we
may want a method that only accepts numbers. This is done using bounded type parameters
with the extends keyword:
public <T extends Number> double sum(T a, T b) {
return [Link]() + [Link]();
}
Here, T extends Number means the type T must be Number or one of its subclasses (like
Integer, Double, Float). Passing a String would result in a compile-time error.
5. Wildcards in Generics
Wildcards are one of the more advanced features of Generics and they are represented by the
question mark symbol (?). A wildcard represents an unknown type. There are three kinds of
wildcards in Java:
5.1 Unbounded Wildcard (?)
Used when the type is completely unknown and any type should be accepted:
public void printList(List<?> list) {
for (Object item : list) {
[Link](item);
}
}
5.2 Upper Bounded Wildcard (? extends T)
Used when you want to accept a specific type or any of its subclasses. This is useful when you
are reading data from a structure:
public double sumList(List<? extends Number> list) {
double sum = 0;
for (Number n : list) sum += [Link]();
return sum;
4
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
5.3 Lower Bounded Wildcard (? super T)
Used when you want to accept a specific type or any of its superclasses. This is useful when
you are writing data into a structure:
public void addNumbers(List<? super Integer> list) {
[Link](10);
[Link](20);
}
The general rule for choosing between upper and lower bounded wildcards is the PECS principle
— Producer Extends, Consumer Super. If a structure produces data (you read from it), use
extends. If it consumes data (you write to it), use super.
6. Type Erasure in Java Generics
One important concept related to Generics is Type Erasure. When a Java program with
Generics is compiled, the type parameters are removed (erased) by the compiler and replaced
with their bounds or Object if no bound is specified. This is done to maintain backward
compatibility with older Java code.
For example, a generic class like Box<T> is converted to Box<Object> internally in the bytecode.
When you use Box<Integer>, the compiler adds the necessary type checks and casts
automatically, but in the final .class file, there is no mention of Integer inside Box.
This means Generics in Java are a compile-time feature only. At runtime, the JVM has no
knowledge of the generic types. This is why you cannot do things like creating an array of a
generic type (new T[]) or checking the instance of a generic type with instanceof.
Type Erasure is the main reason why Java Generics are sometimes considered less powerful
compared to Generics in languages like C# or Kotlin, which support reified generics (where type
information is preserved at runtime). However, for most real-world use cases in Java, compile-
time type safety is more than sufficient.
7. Practical Applications of Generics
Generics are not just a theoretical concept — they are used everywhere in real Java
development. Some of the most common and important places where Generics are actively
used include:
7.1 Java Collections Framework
5
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
The entire Java Collections Framework — List, Set, Map, Queue, Deque, and so on — is built
using Generics. Every time we write ArrayList<String> or HashMap<String, Integer>, we are
using Generics. Without Generics, we would have to store Objects and manually cast every
single element retrieved from a collection.
7.2 Custom Data Structures
Generic classes are ideal for implementing data structures like Stack, Queue, LinkedList, and
Binary Trees that should work with any data type. A single implementation of Stack<T> can be
used as a stack of integers, strings, or any custom objects.
7.3 Utility and Helper Methods
Generic methods are very useful for utility functions like sorting, searching, swapping elements,
or finding minimum/maximum values. The Java standard library has many such generic utility
methods in the Collections class and Arrays class.
7.4 Frameworks and Libraries
Modern Java frameworks like Spring and Hibernate make heavy use of Generics. For example,
Spring's ResponseEntity<T> and JpaRepository<T, ID> are generic types that allow these
frameworks to be type-safe and flexible at the same time.
8. Advantages and Limitations of Generics
8.1 Advantages
• Compile-time type safety eliminates a whole category of runtime errors.
• Code reuse improves significantly as one class or method handles multiple types.
• Removal of unnecessary type casting makes code cleaner and easier to read.
• Better IDE support as editors can provide accurate auto-completion and error
detection.
• Reduced code duplication leads to better maintainability in large projects.
8.2 Limitations
• Cannot instantiate generic types directly (e.g., new T() is not allowed).
• Cannot create arrays of generic types (e.g., new T[] is not allowed).
• Static fields cannot use type parameters since they belong to the class, not an
instance.
• Type information is lost at runtime due to Type Erasure, which can be a limitation in
some advanced scenarios.
• Generics can make code harder to understand for beginners due to complex wildcard
syntax.
6
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
9. Learning Reflection
Before this self-learning activity, I had a very basic understanding of Generics — I knew they
existed and I had used ArrayList<String> many times, but I never really understood what was
happening behind the scenes. After watching the videos and exploring examples, my
understanding has improved significantly.
The concept that surprised me the most was Type Erasure. I had assumed that the JVM knew
the generic types at runtime, but learning that Generics are purely a compile-time mechanism
changed how I think about Java's type system. It also helped me understand why certain things
that seem logical — like creating a generic array — are not allowed in Java.
The PECS principle (Producer Extends, Consumer Super) for wildcards was initially confusing,
but once I understood it with examples, it made a lot of sense. I also realized that Generics are
not just a fancy syntax — they are a core part of how modern Java APIs are designed, and
having a solid understanding of them makes reading Java documentation and frameworks much
easier.
Overall, this self-learning activity gave me a much deeper and more practical understanding of
Generics in Java, and I feel more confident now in reading and writing generic code in my own
programs.
10. Conclusion
Generics in Java are one of the most important features introduced in Java 5, and they remain
just as relevant in modern Java development today. They bring together the benefits of type
safety, code reusability, and cleaner syntax — all without sacrificing runtime performance.
Through this self-learning activity, I understood that Generics go much deeper than just putting
angle brackets around a class name. From bounded type parameters to wildcards, from generic
methods to Type Erasure — each concept builds upon the previous one and has real-world
implications in how Java code is written and maintained.
For any Java developer — whether a student or a professional — mastering Generics is
essential. It forms the foundation of the entire Collections Framework, and understanding it
makes working with advanced Java frameworks and libraries significantly easier and more
intuitive.
11. References
1. Official Java Documentation on Generics:
[Link]
2. Telusko (Navin Reddy) — Java Generics Tutorial (YouTube):
[Link]
7
ENROLLMENT NO.240410107123
SARDAR VALLABHBHAI PATEL INSTITUTE OF TECHNOLOGY
SUB NAME: OBJECT ORIENTED PROGRAMMING SUBJECT CODE:BE04000231
(Channel by Navin Reddy — Widely followed Indian Java educator with detailed Generics
tutorials)
3. CodeWithHarry — Java Programming for Beginners (YouTube):
[Link]
(Channel by Harry — Popular Indian programming educator covering Java concepts including
Generics)
4. Bloch, J. (2018). Effective Java (3rd Edition). Addison-Wesley Professional.
8
ENROLLMENT NO.240410107123