Explanation
This Java program demonstrates the powerful concept of Generics by implementing a single method that can print the elements of an array regardless of its data type.
Let's break down the logic step by step:
- Class Definition (
GenericMethod): The code defines a class namedGenericMethod. In Java, all executable code resides within classes. - Generic Method
printArray:- The core of this program is the
printArraymethod:public static <E> void printArray(E[] inputArray). public static: This makes the method accessible from anywhere and callable directly using the class name (without creating an object).<E>: This is the crucial part that makes the method "generic."Estands for "Element" (though you could use any valid identifier likeTfor "Type"). It's a type parameter that acts as a placeholder for a specific data type. When you call this method, the compiler will infer or you can explicitly specify whatErepresents (e.g.,Integer,Double,Character).void: The method does not return any value.printArray(E[] inputArray): This means the method accepts an array whose elements are of typeE. So, ifEisInteger, it accepts anInteger[]array. IfEisDouble, it accepts aDouble[]array, and so on.- Inside
printArray:for(E element: inputArray): This is an enhanced for-loop (or for-each loop). It iterates through eachelementin theinputArray. The type ofelementisE, which is the type parameter.System.out.printf("%s", element);: This line prints eachelementto the console. The%sformat specifier is used for general string formatting, which works well for various object types as Java'sObjectclass (which all types implicitly extend) has atoString()method.System.out.println();: After printing all elements of an array, this line prints a new line character, ensuring that the output for the next array starts on a fresh line.
- The core of this program is the
- Main Method (
main):public static void main(String[] args): This is the entry point of any Java application.- Array Creation:
Integer[] intArray = {1,2,3,4,5};: An array ofIntegerobjects is created and initialized. Note thatIntegeris a wrapper class for the primitiveint. Generics in Java work with object types, not primitive types directly.Double[] doubleArray = {1.1,2.2,3.3,4.4,5.5};: An array ofDoubleobjects.Character[] charArray = {'H','E','L','L','O'};: An array ofCharacterobjects.
- Calling
printArray:System.out.println("Array intArray contains");printArray(intArray);: Here, theprintArraymethod is called withintArray. The compiler automatically infers that for this call,Eshould beInteger.- Similar calls are made for
doubleArrayandcharArray, demonstrating how the sameprintArraymethod can handle different array types without needing to be rewritten or overloaded for each type.
In essence, this program showcases how generics allow you to write flexible, reusable, and type-safe code that operates on different data types without sacrificing compile-time safety.