Understanding generics in Java

  • Eclipse: Oxygen
  • Java: 1.8

This tutorial deals with the type parameters that are used in generics in Java. The type parameters related to generics are described here. Here its use in the program is shown. Users will be able to better use generics with this.

In the following program we write generic functions that can be called with different types of arguments depending on the type of arguments passed to the generic method, the compiler manages each method without any runtime error.

In the following program, we demonstrate that using generics converts runtime exceptions into a compile-time exception.

Here we want to apply the restriction at the time of defining List, hence we create a list with String specified. Now compiler does not allow any other data type value.


Exception in thread “main” java.lang.Error: Unresolved compilation problems:

     The constructor Data<String>(double) is undefined

     The constructor Data<String>(int) is undefined

In the following program, we demonstrate the entire operation through the Integer object.


Element: 10

Element: 20

Element: 30

Element: 40

Element: 50

Contributed by: Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu