group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
263 Members
Join this group to post and comment.
DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
11 Feb 2019

Why we need Generics in Java?

Errors are integral part of coding. Some errors occur at compile time and some errors occur at run time. Errors which occur at compile time can be easily identified and can be removed. But, run time errors occur when an application is running in real time. If they happen, they cause abrupt termination of an application.

ClassCastException is also such an exception which happens only at run time. It occurs when data of one type can not be casted to another type. You will never get a single clue about this exception during compilation. Look at the below code which throws ClassCastException at run time. But, you will never be get notified about this exception at compile time.

Generics are introduced in Java 5 to provide the type checking at compile time. If you use generics, you need not to perform the type casting explicitly. Java compiler applies strong type checking if you use generics in your code and shows errors if the code violates the type safety. Thus removing the risk of ClassCastException.

Therefore, To write the type safety code and to remove the risk of ClassCastException at run time, we need generics.

Archana Priyadarshini
Archana Priyadarshini
Computer Science
2mos ago

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods

Code that uses generics has many benefits over non-generic code:

  1. Stronger type checks at compile time.A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
  2. Elimination of casts.
  3. Enabling programmers to implement generic algorithms.

    By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.