Menu
Coddy logo textTech

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 String

Generic methods are particularly useful in utility classes where you need flexible, reusable operations without creating a generic class.

challenge icon

Challenge

Easy

Let'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 type T and returns the last element. If the array is empty, return null.

    swap - A generic method that takes an array of type T and two integer indices, then swaps the elements at those positions. This method doesn't return anything.

    printWithLabel - A generic method with two type parameters K and V. It takes a label of type K and a value of type V, 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. Use getLast to get the last element and print: Last word: [result]

    Next, create an Integer[] array containing both numbers. Call swap to swap the elements at indices 0 and 1, then print: After swap: [first], [second]

    Finally, demonstrate the two-parameter generic method by calling printWithLabel twice:

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

Generic 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming