Generic method
- Java course
- Intermediate
- Lesson 83/116
- 5 min
Learn generic methods with <T>.
Generic method
A generic method is a method that declares its own type parameter. You write static <T> T identity(T value) { return value; }; the <T> comes before the return type. You do not need to pass the type at the call site; the compiler infers it from the argument.
For example identity("Hello") returns String, while identity(42) returns Integer. The same method works type-safely for different types. Generic methods can live in non-generic classes too.
Type inference
The Java compiler infers the type from the argument at a generic method call. When you write identity("Hello") the compiler decides T is String; for identity(42) it becomes Integer.
You can also be explicit: Main.<String>identity("Hello"). Most of the time this is unnecessary. Thanks to inference the code stays short and readable; passing the wrong type still gives a compile error.
Practice Write the identity generic method
Define an identity generic method: static <T> T identity(T value) whose body is return value;. In main, call it with String s = identity("Hello"); and print it with System.out.println(s);.
Starter code
// Define the identity generic method
// main: call identity and printlnSample solution
public class Main {
static <T> T identity(T value) {
return value;
}
public static void main(String[] args) {
String s = identity("Hello");
System.out.println(s);
}
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the generic method concepts
| Term | Meaning |
|---|---|
<T> T identity(T) |
Generic method signature |
T identity(T) |
Non-generic signature |
return value |
Return value |
identity("Hello") |
Call with type inference |
2 Where does <T> go in a generic method?
- At the end of the method body
- After the class name
- Before the return type Correct answer
- Below the parameter list
Explanation: <T> comes before the return type; e.g. static <T> T identity(T value).
3 Complete the generic method declaration
static ____ T identity(T value) {
return value;
}
static <T> T identity(T value) {
return value;
}
Explanation: <T> gives the method a type parameter.