Java Generic

Java Generic :

A parameterized type that operates by a class or an interface is called generic. It is introduced in java-5. It facilitate to write algo which is independent from any specific data type and type safety.

Through Generic its possible to create a single class or method that automatically works with all data types such as Integer, String Float, Double etc. It provide ability to reuse existing code safely and easily.

Note : Generic works only with Object type such as Integer, Float. It can’t work with primitive type.

Example :

You can better understand Generic through below code :


* @author pradeep
public class GenericTest {

public static void main(String args[]) {

GenericExample<Integer> gt = new GenericExample(50);
int a = gt.getObject();
GenericExample<String> gt2 = new GenericExample("Pradeep Yadav");
String b = gt2.getObject();

class GenericExample<T> {

T obj;

public GenericExample(T obj2) {
obj = obj2;

public T getObject() {
return obj;

Output :

Pradeep Yadav