Passing primitive values while instantiating a parameterized type (generic) in Java?


Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.

Example

 Live Demo

class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      std1.display();
      Student<String> std2 = new Student<String>("25");
      std2.display();
      Student<Integer> std3 = new Student<Integer>(25);
      std3.display();
   }
}

Output

Value of age: 25.5
Value of age: 25
Value of age: 25

Passing primitive values

The Generic types are intended for reference types, you cannot pass primitive datatypes to them if you do so a compile time error will be generated.

Example

 Live Demo

class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      Student<String> std2 = new Student<String>("25");
      Student<int> std3 = new Student<int>(25);
   }
}

Compile time error

GenericsExample.java:11: error: unexpected type
      Student<int> std3 = new Student<int>(25);
          ^
   required: reference
   found: int
GenericsExample.java:11: error: unexpected type
      Student<int> std3 = new Student<int>(25);
                                    ^
   required: reference
   found: int
2 errors

Example

 Live Demo

public class GenericMethod {
   <T>void sampleMethod(T[] array) {
      for(int i=0; i<array.length; i++) {
         System.out.println(array[i]);
      }
   }
   public static void main(String args[]) {
      GenericMethod obj = new GenericMethod();
      Integer intArray[] = {45, 26, 89, 96};
      obj.sampleMethod(intArray);
      String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
      obj.sampleMethod(stringArray);
      char charArray[] = {'a', 's', 'w', 't'};
      obj.sampleMethod(charArray);
   }
}

Output

GenericMethod.java:16: error: method sampleMethod in class GenericMethod cannot be applied to given types;
      obj.sampleMethod(charArray);
      ^
   required: T[]
   found: char[]
   reason: inference variable T has incompatible bounds
      equality constraints: char
      upper bounds: Object
   where T is a type-variable:
      T extends Object declared in method <T>sampleMethod(T[])
1 error

Updated on: 09-Sep-2019

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements