Generic Subprograms
Generic Subprograms
1. Type Independence:
○ Allows the subprogram to handle data of different types
(e.g., integs, floats, or user-defined types).
2. Code Reusability:
○ Instead of writing multiple versions of a subprogram for
different data types, you write a single generic version.
3. Compile-Time Type Checking:
○ Type safety is ensured during compilation, avoiding
runtime errors in strongly typed languages.
4. Flexibility:
○ They work seamlessly with any type provided during
invocation.
// String array
String[] strArray = {"Hello", "World"};
printArray(strArray);
// Double array
Double[] doubleArray = {1.1, 2.2, 3.3};
printArray(doubleArray);
}
}
Output:
1234
Hello World
1.1 2.2 3.3
1. Data Structures:
○ Used in generic collections like ArrayList or
HashMap in Java or std::vector in C++.
2. Sorting and Searching:
○ Generic algorithms for sorting or searching, irrespective
of data type.
3. Utility Functions:
○ Functions for printing, comparing, or swapping values
of various types.