Online Classes

Results can only be achieved if you have the focused direction and crystal clear knowledge. To achieve this, you need a mentor. We will help you out by connecting with an expert mentor in the field.

Learn More

Article

Java Generic Methods

1 min 17 sec read

What are generic methods ?

Suppose you have an integer array of 4 elements

Integer[] iray = {10,20,30,40};

And one character array of 4 characters

Character[] cray = {'c','o','d','z'}

Now if you want to print the elements in both of these arrays you have to write two different print methods. And Suppose in future there is also Float[] array and double[] array too. Then think you have to write a print method to display the elements of array four times.

So here, Generic Methods comes into existence. One method can handle different types . Thats why it is called as generic Type.

Program before using Generic Methods

import java.util.*;

public class JavaGenericMethods {
  public static void main(String[] args)
  {
    Integer[] iray = {10,20,30,40};
    Character[] cray = {'c','o','d','z'};
    Double[] dray = {10.2,12.3,14.6};
    
    printElements(iray);
    printElements(cray);
    printElements(dray);
  }

  
  public static void printElements(Integer[] i)
  {
    for(Integer x: i )
    {
      System.out.printf("%s ", x);
    }
    System.out.println();
  }
  
  public static void printElements(Character[] c)
  {
    for(Character x: c )
    {
      System.out.printf("%s ", x);
    }
    System.out.println();
  }
  
  public static void printElements(Double[] i)
  {
    for(Double x: i )
    {
      System.out.printf("%s ", x);
    }
    System.out.println();
  }
}

Output :-

10 20 30 40 
c o d z 
10.2 12.3 14.6 

Program after using Generic Methods

import java.util.*;

public class JavaGenericMethods {
  public static void main(String[] args)
  {
    Integer[] iray = {10,20,30,40};
    Character[] cray = {'c','o','d','z'};
    Double[] dray = {10.2,12.3,14.6};
    
    printElements(iray);
    printElements(cray);
    printElements(dray);
  }

  
  public static <T> void printElements(T[] i)
  {
    for(T x: i )
    {
      System.out.printf("%s ", x);
    }
    System.out.println();
  }
}

Output :-

10 20 30 40 
c o d z 
10.2 12.3 14.6 

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor