Generic Methods in Java

1 min 17 sec read Basic


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  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 

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python