Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are type parameters in Java?

Tarun Telang


We can use Java Generics to specify one or more type parameters to classes and methods. This allows for more flexibility and robust code. We can make a class or method work with any type that meets specific criteria by specifying a type parameter. This makes our code more reusable and easier to maintain.


For example, consider the following class:

public class MyClass<T> {
 // ...
Syntax of using type parameters in Java


This class has a type parameter called T. This means that the class can work with any type that is specified when the class is instantiated.


For example, we could create an instance of MyClass like this:

MyClass<String> myObj = new MyClass<String>();
Instantiating a class using String type parameter

In the above example, we are saying that our MyClass object will work with the String objects. We could also create an instance of MyClass like this:

MyClass<Integer> myObj = new MyClass<Integer>();
Instantiating a class using Integer type parameter.

In this example, we say that our MyClass object will work with the Integer objects. We can use any type we want as the type parameter, including our own custom classes.

We use type parameters because it makes our code more flexible and reusable. For example, consider a method that sorts an array of objects:

import java.util.Arrays;
class Sorter<T> {
    public void sort(T[] arr) {
    public static void main(String args[] ) {
        Sorter<Integer> intSorter = new Sorter<>();
        Integer[] intArr = new Integer[]{3,2,1};

        Sorter<String> strSorter = new Sorter<>();
        String[] strArr = new String[]{"c", "b", "a"};

Java program to sort an array of any type

The sort() method can sort an array of any type that is specified when the method is called. If we didn't use type parameters, we would have to write a separate sort method for each type of array we wanted to sort.

With type parameters, we can write one sort method that can be used for both String and Integer arrays.



View all Courses

Keep Exploring