You are here: Home / Topics / Program to explain Generic Method in Java

Program to explain Generic Method in Java

Filed under: Java on 2024-04-12 18:37:56

// Program to explain Generic Method.

public class  GenericTest7 
{
// generic method printArray
public static <T> void printArray(T[ ] inputArray) 
{
 // display array elements
 for (T element : inputArray)
  System.out.printf("%s  ", element);

 System.out.println();
}

public static void main(String args[ ]) 
{
 // create arrays of Integer, Double and Character
 Integer[ ] i = { 1, 2, 3, 4, 5, 6 };
 Double[ ] d = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
 Character[ ] c = { 'H', 'E', 'L', 'L', 'O' };

 System.out.println("Array i contains:");
 printArray(i); 
 
 System.out.println("\nArray d contains:");
 printArray(d); 
 
 System.out.println("\nArray c contains:");
 printArray(c); 
}
}

 

Output:

Array i contains:
1  2  3  4  5  6

Array d contains:
1.1  2.2  3.3  4.4  5.5  6.6  7.7

Array c contains:
H  E  L  L  O


About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.