Lesson 3 of 715 minModule progress 0%

Module 12: Generics and Type Safety

Generic Methods

Write methods that infer types and stay readable at the call site.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Declare a generic method correctly
  • Understand method-level type inference
  • Avoid turning entire classes generic without need

Generic methods declare type parameters before the return type: That is what makes the method flexible on its own.

This is useful in utility code: A whole class may not need a type parameter even though one method does.

Type inference usually keeps the call clean: Java often figures out the type from the argument or assignment context.

Use this tool to keep APIs precise: Put flexibility only where it is actually needed.

Runnable examples

One reusable identity method

public static <T> T first(T value) {
    return value;
}

System.out.println(first("Java"));

Expected output

Java

Mini exercise

Write a generic method that returns the second of two values with the same type.

Summary

  • Generic methods localize flexibility to one operation.
  • The type parameter appears before the return type.
  • Use method-level generics when the class itself should stay simple.

Next step

After the basics, add bounds so generic code can require certain capabilities.

Sources used

Advertisement

Lesson check

Where do generic method type parameters appear?

Next lesson →