Generic Methods
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 55 of 87.
While generic classes make entire classes work with different types, sometimes you only need a single method to be generic. A generic method declares its own type parameter, independent of any class-level generics.
The type parameter appears before the return type in the method signature:
public class Utility {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
}
String[] names = {"Alice", "Bob"};
Integer[] numbers = {1, 2, 3};
Utility.printArray(names); // Works with String[]
Utility.printArray(numbers); // Works with Integer[]Notice the <T> placed between the modifiers and the return type. This declares T as a type parameter for this specific method. The compiler infers the actual type from the arguments you pass.
Generic methods can also return the generic type:
public static <T> T getFirst(T[] array) {
if (array.length > 0) {
return array[0];
}
return null;
}
String first = getFirst(new String[]{"a", "b"}); // Returns "a"You can use multiple type parameters when needed:
public static <K, V> void printPair(K key, V value) {
System.out.println(key + ": " + value);
}
printPair("Age", 25); // String and Integer
printPair(1, "First"); // Integer and StringGeneric methods are particularly useful in utility classes where you need flexible, reusable operations without creating a generic class.
Challenge
EasyLet's build a utility toolkit that showcases the flexibility of generic methods. You'll create a class with reusable methods that work with any type, demonstrating how generic methods can exist independently of generic classes.
You'll organize your code across two files:
ArrayUtils.java: Create a utility class containing generic methods for working with arrays. Your class should have three static generic methods:getLast- A generic method that takes an array of typeTand returns the last element. If the array is empty, returnnull.swap- A generic method that takes an array of typeTand two integer indices, then swaps the elements at those positions. This method doesn't return anything.printWithLabel- A generic method with two type parametersKandV. It takes a label of typeKand a value of typeV, then prints them in the format:[label]: [value]Main.java: Put your generic methods to work! You'll receive four inputs: two words (Strings) and two numbers (integers).First, create a
String[]array containing both words. UsegetLastto get the last element and print:Last word: [result]Next, create an
Integer[]array containing both numbers. Callswapto swap the elements at indices 0 and 1, then print:After swap: [first], [second]Finally, demonstrate the two-parameter generic method by calling
printWithLabeltwice:- Once with the first word as the label and the first number as the value
- Once with the first number as the label and the second word as the value
You will receive four inputs in order: first word, second word, first number, second number.
Notice how each method declares its own type parameter(s) with <T> or <K, V> before the return type. The compiler infers the actual types from the arguments you pass—no need to specify them explicitly when calling the methods!
Cheat sheet
A generic method declares its own type parameter, independent of any class-level generics. The type parameter appears before the return type in the method signature.
Basic generic method syntax:
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}The <T> is placed between the modifiers and the return type. The compiler infers the actual type from the arguments you pass.
Generic methods can return the generic type:
public static <T> T getFirst(T[] array) {
if (array.length > 0) {
return array[0];
}
return null;
}Multiple type parameters can be used:
public static <K, V> void printPair(K key, V value) {
System.out.println(key + ": " + value);
}
printPair("Age", 25); // String and Integer
printPair(1, "First"); // Integer and StringGeneric methods are useful in utility classes for flexible, reusable operations without creating a generic class.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read inputs
String firstWord = scanner.nextLine();
String secondWord = scanner.nextLine();
int firstNumber = scanner.nextInt();
int secondNumber = scanner.nextInt();
// TODO: Create a String[] array containing both words
// TODO: Use ArrayUtils.getLast to get the last element
// Print: "Last word: [result]"
// TODO: Create an Integer[] array containing both numbers
// TODO: Call ArrayUtils.swap to swap elements at indices 0 and 1
// Print: "After swap: [first], [second]"
// TODO: Call ArrayUtils.printWithLabel with firstWord as label and firstNumber as value
// TODO: Call ArrayUtils.printWithLabel with firstNumber as label and secondWord as value
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System