- Prerequisites
- 1.1 Generic Types
- Covers
- Type parameter declaration · Multiple type parameters · Naming conventions
- Related
- 2.1 Bounded Type Parameters · 2.4 Type Inference
On this page
1Concept / Definition
A type parameter is a name introduced in a generic declaration that stands for a type to be supplied later. It is declared in angle brackets after a class or interface name, or before a method's return type, and can be used wherever a type is expected within its scope, subject to the restrictions of erasure (3.3).
Type parameters are what make a declaration generic. Without them, one class or method cannot express that its input and output types are related, for example that get() returns the same type that put() accepted.
2Why It Exists
Before generics, reusable code worked with Object. A Map accepted any key and any value, and every read needed a cast such as (Order) map.get(id). A wrong cast compiled cleanly and failed at run time with a ClassCastException, often far from the code that inserted the wrong object.
Type parameters let a declaration name the types it works with and state how they relate. Map<K, V> says that keys are all one type and values all another; Function<T, R> says the function takes a T and returns an R. The compiler checks every use against these names, inserts the casts itself and reports mistakes at compile time, so one implementation can be reused safely for any type.
3Core Concepts
Type parameter declaration
A declaration lists one or more names, each optionally followed by a bound: <T>, <T extends Number> (2.1). A class's type parameters are in scope for all instance members but not for static members, because static members are shared by all parameterisations. A method's type parameters are in scope only within that method.
Multiple type parameters
Several parameters are separated by commas: Map<K, V>, Function<T, R>, BiFunction<T, U, R>. Each is independent; one may be used in the bound of another (<T, C extends Collection<T>>).

Naming conventions
By convention type parameters are single uppercase letters, which distinguishes them from class names at a glance. The JDK uses a consistent set:

Longer names (<ENTITY>, <TResult>) are occasionally used in complex frameworks, but single letters remain the norm; readability comes from keeping the number of parameters small.
4How It Works Internally
Scope of a type parameter
A class's type parameters are in scope in its instance fields, constructors, instance methods and non-static nested classes. They are not in scope in static members, because a static field or method is shared by every parameterisation of the class: Cache<String, Order> and Cache<Long, User> share the same static state, so K has no single meaning there. A method's type parameters are visible only inside that method, and a constructor can declare its own in the same way.

Figure 3 sums up the rule: anything that belongs to an instance can use the class's parameters, anything static cannot, and a generic method or constructor brings its own. A static nested class is a separate class, so it declares its own parameters too, as Map.Entry<K, V> does.
Erasure of type parameters
After type-checking, javac erases each type parameter to its leftmost bound: <T> becomes Object, <T extends Number> becomes Number, and <T extends Number & Comparable<T>> becomes Number. The compiler inserts casts where values come back out, so the bytecode works with the erased types. Because of this, a type parameter cannot be used where a run-time type is needed: new T(), T.class, new T[10] and x instanceof T do not compile.
What reflection can still see
The declarations survive in the class file's Signature attribute, so reflection can report them. Pair.class.getTypeParameters() returns TypeVariable objects named A and B, each with its bounds. What reflection cannot recover is the type argument used by a particular object, because an instance of Pair<String, Integer> and one of Pair<Order, Long> are the same class at run time.
5APIs / Features / Syntax
Type parameters can be declared on classes, interfaces, records, methods and constructors. A method declares them before the return type, and callers can usually let the compiler infer them or, when inference needs help, supply them explicitly.
// class, interface and record
public class Box<T> { private T value; }
public interface Converter<S, T> { T convert(S source); }
public record Pair<A, B>(A first, B second) { }
// generic method: type parameter before the return type
public static <T> List<T> listOf(T first, T second) { return List.of(first, second); }
// bounds: one class first, then interfaces, joined with &
public static <T extends Number & Comparable<T>> T max(T a, T b) { return a.compareTo(b) >= 0 ? a : b; }
// explicit type argument when inference needs help
List<String> names = Collections.<String>emptyList();Recursive bounds such as <T extends Comparable<T>> say that T can be compared with other values of the same type. They are common in sorting and ordering utilities and in builder APIs that return the concrete builder type.
6Practical Examples
Example 1 — Multiple parameters and scope
public record Pair<A, B>(A first, B second) {
public <C> Pair<A, C> withSecond(C newSecond) { // method adds its own C
return new Pair<>(first, newSecond);
}
}
public class Cache<K, V> {
private final Map<K, V> store = new ConcurrentHashMap<>();
public V get(K key, Function<? super K, ? extends V> loader) {
return store.computeIfAbsent(key, loader);
}
// static <K> void helper(K k) { } // fine: this K is a new method parameter,
// static K shared; // error: class K not usable in static context
}The Pair record uses two class type parameters, A and B, while withSecond declares its own C, so it can return a pair whose second element has a different type. Cache<K, V> keeps keys and values related: a Cache<String, Order> can only store orders under string keys, and get returns an Order without a cast.
Example 2 — Mini program: a typed settings store
Problem. A service keeps its settings in a Map<String, Object>, so every read needs a cast and a wrong value type fails only when the setting is used. One type parameter on the key, Key<T>, lets the compiler connect each key with the type of its value, while one map still holds all of them.
public class TypedSettings {
// T links a key to the type of its value
record Key<T>(String name, Class<T> type, T defaultValue) {}
static final class Settings {
private final Map<Key<?>, Object> values = new HashMap<>();
<T> Settings put(Key<T> key, T value) {
values.put(key, key.type().cast(value)); // checked at run time
return this;
}
<T> T get(Key<T> key) {
Object v = values.get(key);
return v == null ? key.defaultValue() : key.type().cast(v);
}
}
static final Key<Integer> PORT = new Key<>("port", Integer.class, 8080);
static final Key<Duration> TIMEOUT =
new Key<>("timeout", Duration.class, Duration.ofSeconds(2));
static final Key<Boolean> TLS = new Key<>("tls", Boolean.class, false);
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
Settings s = new Settings().put(PORT, 9443).put(TLS, true);
int port = s.get(PORT); // an Integer, no cast
Duration timeout = s.get(TIMEOUT); // not set: the default
boolean tls = s.get(TLS);
System.out.println("port=" + port + " timeout=" + timeout.toMillis()
+ "ms tls=" + tls);
// s.put(PORT, "9443"); // error: String is not Integer
Key raw = PORT; // a raw key passes the compiler ...
try {
s.put(raw, "9443");
} catch (ClassCastException e) { // ... but not the Class token
System.out.println("rejected: " + e.getMessage());
}
}
}port=9443 timeout=2000ms tls=true
rejected: Cannot cast java.lang.String to java.lang.Integer
Why it behaves this way. put and get are generic methods whose T is inferred from the key (Figure 4). For PORT, a Key<Integer>, put accepts only an Integer and get returns one, so int port = s.get(PORT) needs no cast. The map itself is Map<Key<?>, Object>, because its entries have different value types. The Class<T> component closes the gap that raw types leave: type().cast checks the value at run time, so a value smuggled past the compiler through a raw Key is rejected at put, not when someone reads it. This pattern is called a typesafe heterogeneous container.
Example 3 — Shadowing the class parameter
A common slip is to declare a method type parameter with the same name as the class's. The method's T then hides the class's T, and the two are unrelated even though they look the same.
public class Box<T> {
private T value;
// This <T> is a NEW type parameter that hides the class's T
public <T> void set(T newValue) {
// value = newValue; // does not compile: the two Ts are different types
}
// Correct: use the class's T without redeclaring it
public void put(T newValue) { this.value = newValue; }
}Remove the method-level declaration, or give a genuinely different parameter a different name such as U. Most IDEs warn about this shadowing.
Example 4 — A recursive bound
public static <T extends Comparable<T>> T largest(List<T> items) {
T best = items.getFirst();
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
largest(List.of(3, 9, 4)); // 9: Integer implements Comparable<Integer>
largest(List.of("pear", "apple")); // pear
// largest(List.of(new Object())); // does not compile: Object is not ComparableThe bound makes compareTo available on T and rejects types that cannot be ordered at compile time, rather than failing at run time.
Example 5 — What reflection can see of a type parameter
Problem. Section 4 says that type parameters are erased but their declarations survive. This program asks reflection for the type parameters of a record and the signature of a bounded generic method.
public class TypeParamReport {
record Pair<A, B>(A first, B second) {}
static <T extends Number & Comparable<T>> T max(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
public static void main(String[] args) throws Exception {
for (TypeVariable<?> v : Pair.class.getTypeParameters())
System.out.println("Pair declares " + v.getName()
+ ", bounds " + Arrays.toString(v.getBounds()));
Method m = TypeParamReport.class.getDeclaredMethod("max",
Number.class, Number.class); // looked up by its erasure
String erased = m.toString(), generic = m.toGenericString();
System.out.println("erased: " + erased.replace("java.lang.", ""));
System.out.println("generic: " + generic.replace("java.lang.", ""));
Pair<String, Integer> p = new Pair<>("a", 1);
System.out.println("instance: "
+ Arrays.toString(p.getClass().getTypeParameters()));
}
}Pair declares A, bounds [class java.lang.Object]
Pair declares B, bounds [class java.lang.Object]
erased: static Number TypeParamReport.max(Number,Number)
generic: static <T extends Number & Comparable<T>> T TypeParamReport.max(T,T)
instance: [A, B]Why it behaves this way. getTypeParameters() reads the Signature attribute, so it finds A and B, each bounded by Object. The method has to be looked up by its erased parameter types: <T extends Number & Comparable<T>> erases to its leftmost bound, so the descriptor uses Number, and toString() shows that erased form, while toGenericString() rebuilds the declaration (the program drops the java.lang. prefixes to keep the lines short). The last line shows the limit: the instance's class reports the parameter names A and B, never the arguments String and Integer.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| Using the class's type parameter in a static member (static T defaultValue;) | Does not compile: static members are shared by every parameterisation, so T has no single meaning there | Declare a method type parameter (static <T> Box<T> of(T v)), or keep a Class<T> in an instance field |
| Expecting the type to exist at run time (new T(), new T[n]) | Does not compile because of erasure; workarounds with unchecked casts move the failure to run time | Ask the caller for a Supplier<T> or a Class<T>, e.g. create(Supplier<T> factory) |
| Shadowing: a generic method in a generic class that redeclares T | A second, unrelated T; the code looks right and fails to compile, or silently accepts other types (Example 3) | Use the class's T, or name the method's parameter U |
| Too many or unclear parameters (Processor<A, B, C, D>) | Hard to read, to document and to infer; error messages become long | Group related types into a named type, or fix some in a subtype: OrderProcessor implements Processor<Order, Receipt> |
| Raw types (Pair p instead of Pair<String, Integer>) | Type checking is switched off for that variable, and unchecked warnings hide real mistakes | Always give type arguments; use Pair<?, ?> when they do not matter |
| Naming a type parameter like a class (class Repository<Order>) | Order is now a type variable that hides the Order class; order.total() no longer compiles, with a confusing message | Keep single-letter names (T, E, K, V, R) for type parameters |
8Performance & Production Considerations
Type parameters cost nothing at run time. After erasure the bytecode is the same as hand-written code that uses Object and casts, and the JIT compiler removes most of those casts. The real costs are elsewhere: type arguments must be reference types, so List<Integer> boxes every number, which matters in large collections and hot loops; and complex generic signatures slow down humans more than machines, because compiler error messages about inference failures can be long and hard to read.
9Architecture & Design Considerations
In API design, every type parameter is part of the contract and is hard to remove later. Add one only when it expresses a real relationship between types that callers benefit from. Infrastructure code, such as repositories, caches, result wrappers and event envelopes, gains the most, because one tested implementation then serves every domain type. Domain classes usually gain little: Order and Invoice read better as concrete types than as Document<T>.
Keep public signatures to one to three type parameters with conventional names. When a parameter is fixed in practice, fix it in a subtype. When a method needs the run-time type, design the API to receive it explicitly, through a Class<T> or a type reference, rather than hiding reflection inside the library.
10Interview Questions & Answers
What do the type parameter names E, K, V, T and R conventionally mean?
These are naming conventions used throughout the JDK and most Java libraries, not language rules. E stands for the element type of a collection, as in List<E> or Set<E>. K and V stand for the key and value types of a map, as in Map<K, V>. T stands for a general type, with U, V and S used for a second, third or fourth type when needed. R stands for the result or return type of a function, as in Function<T, R>. Using single uppercase letters makes type parameters easy to tell apart from class names, and following the convention means readers understand a signature at a glance.
Can a static method or field use the class's type parameter?
No. A static field or method belongs to the class itself and is shared by every parameterisation, so Cache<String, Order> and Cache<Long, User> share the same static members and the class's K or V has no single meaning there. Writing static T value or using T in a static method body does not compile. A static method can declare its own type parameter instead, as in static <T> Box<T> of(T value), which is how factory methods such as List.of work. If static code needs a type, pass it in as a method type parameter or as a Class<T> argument.
Can one type parameter be used in the bound of another?
Yes. Type parameters declared in the same section can refer to each other in their bounds, and the order does not matter. For example, <T, C extends Collection<T>> requires C to be a collection of T, so a method can accept and return the same kind of collection. A parameter can even refer to itself, as in the recursive bound <T extends Comparable<T>>. These dependent bounds let a signature express precise relationships that the compiler then checks at every call site.
How many type parameters are too many for a public API?
There is no fixed limit, but beyond two or three type parameters a public API becomes hard to read, document and use, and the compiler's type inference and error messages become harder to follow. Many parameters often mean the abstraction is doing too much, or that some types are always the same in practice. Options are to fix those types in a subtype, such as OrderHandler implements Handler<Order, Receipt>, to group related types into a single named type, or to split the API into smaller pieces. The JDK itself rarely goes beyond three, as in BiFunction<T, U, R>.
Where can type parameters be declared?
On classes, interfaces and records after the name, and on methods and constructors before the return type or the constructor name, as in public <T> List<T> listOf(T a, T b) or <S> Label(S source). Enums, anonymous classes and lambdas cannot declare type parameters, and neither can a field or a local variable on its own: they can only use parameters already in scope. Exceptions cannot be generic either, because a catch clause would need the type at run time.
What does this program print?
public class ShadowQuiz {
static class Box<T> {
T value;
<T> T echo(T t) { return t; } // a new T, unrelated to Box's T
}
public static void main(String[] args) {
Box<String> b = new Box<>();
Integer n = b.echo(42);
System.out.println(n + 1);
System.out.println(b.<Double>echo(1.5));
System.out.println(b.value);
}
}It prints 43, then 1.5, then null. The <T> on echo declares a new type parameter that shadows the class's T, so for a Box<String> the method still accepts any type: the first call infers Integer, and the second gives Double explicitly. value was never set, so it is null. The code compiles, which is the danger of shadowing; most IDEs and static analysis tools flag it.
If type parameters are erased, how can reflection report their names and bounds?
Erasure removes type arguments from objects and from the bytecode that runs, but javac also writes a Signature attribute for each generic class, method and field. Class.getTypeParameters(), Method.toGenericString() and Field.getGenericType() read that attribute, which is how Example 5 prints A, B and the bounds of max. What reflection cannot recover is the argument a particular object was created with, because the object only refers to its erased class.
A constructor can declare its own type parameter. What does this program print?
public class GenericConstructor {
static final class Label<T> {
final T value;
final String source;
// S is the constructor's own type parameter
<S> Label(S source, Function<? super S, ? extends T> f) {
this.value = f.apply(source);
this.source = String.valueOf(source);
}
}
public static void main(String[] args) {
Label<Integer> length = new Label<>("hello", String::length);
Label<String> tag = new <Integer>Label<String>(7, i -> "#" + i);
System.out.println(length.source + " -> " + length.value);
System.out.println(tag.source + " -> " + tag.value);
}
}It prints hello -> 5, then 7 -> #7. Label<T> is generic in its value type, and the constructor adds its own S for the source type, so one class turns a String into an Integer label and an Integer into a String label. With the diamond, both T and S are inferred. The second line gives S explicitly with the rare syntax new <Integer>Label<String>(...); explicit constructor type arguments cannot be combined with the diamond.
A developer writes class OrderRepository<Order> implements Repository<Order> and now order.total() does not compile. Why?
The <Order> after the class name declares a type parameter named Order, which shadows the real Order class inside OrderRepository. In the body, Order is now an unknown type with bound Object, so total() is not found, and the error message mentions a type variable that looks like the class. The intent was a class that fixes the type argument: class OrderRepository implements Repository<Order>, without a type parameter section. Single-letter names avoid this confusion.
A generic Cache<K, V> keeps its entries in a static Map<Object, Object> shared by all instances. In production, a Cache<String, Order> occasionally returns a User and a ClassCastException follows. What is wrong, and how do you fix it?
Static state is shared by every parameterisation, so the Cache<String, Order> and a Cache<String, User> write into the same map, and identical keys such as "42" collide. The compiler could not stop it, because the static map had to use Object and the class casts its contents to V, which hides the problem behind an unchecked cast. Make the map an instance field, so each cache owns its own entries, and remove the unchecked cast. If a shared store is genuinely needed, include the value type in the key, or use a typed key such as Key<T> (Example 2).
A generic factory needs to create instances of T. Would you ask callers for a Class<T> or a Supplier<T>?
A Supplier<T>, such as Order::new, is checked by the compiler, works for any constructor or factory method, needs no reflection and runs as fast as a direct call. A Class<T> is more flexible at run time: it can also check values with cast, appear in error messages and be looked up by name, which frameworks need, but creating an instance with getDeclaredConstructor().newInstance() needs a no-argument constructor, reflection and handling of checked exceptions. Prefer Supplier<T> for creation and Class<T> when the type itself has to be inspected or checked.
Design a typed configuration API for a platform used by many services.
Expose typed keys rather than strings: Key<T> with a name, a Class<T>, a default value and a validator, declared as constants in each module, and a Settings object with generic get(Key<T>) and put(Key<T>, T) methods (Example 2). Callers then get the right type without casts, and the Class<T> converts and checks values read from files or environment variables when the service starts, so a bad value fails fast with the key's name in the message. Keep the store Map<Key<?>, Object> private, and make settings immutable after startup.
A published interface Processor needs a type parameter. Do you add it to the existing interface or publish a new one?
Adding a type parameter to an existing interface is binary compatible, because the erased signatures stay the same, and source compatible in the weak sense that old callers become raw-type users with unchecked warnings. That keeps one interface but leaves a long tail of raw usages that silently lose type checking. A new interface, such as TypedProcessor<T>, keeps old callers unchanged and gives new callers a clean API, at the cost of two types to maintain and an adapter between them. For widely used libraries the gradual path usually wins: add the parameter, publish migration notes, and track the raw usages until they reach zero.
What standards would you set for type parameters in the public APIs of an organisation's shared libraries?
Keep each public type or method to one to three type parameters with the conventional names, and require a type parameter to express a real relationship between positions in the signature, not just generality. Use wildcards in parameters and exact types in return values (Chapter 2). Ask for a Class<T> or a type token where a library needs the type at run time, instead of hidden reflection. Enforce the rules where they are cheap: compile with -Xlint:all -Werror, add API review to the release checklist, and run a binary-compatibility check such as japicmp, since changes to bounds alter erased signatures and break compiled callers.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Type parameters are declared in angle brackets, optionally with bounds.
- Class parameters are not visible in static members; method parameters are local to the method.
- Use conventional single-letter names: T, E, K, V, R.