Java Bounded Types
Why Type Parameters Need Bounds
An unrestricted type parameter T can be any reference type. That's flexible, but it means the compiler knows nothing about T except that it's an Object. Inside generic code, you can only call Object's methods (equals, hashCode, toString) on a T:
import java.util.*;
public class NoBound {
static <T> double sum(List<T> values) {
double total = 0;
for (T v : values) total += v.doubleValue();
return total;
}
}
NoBound.java:6: error: cannot find symbol
for (T v : values) total += v.doubleValue();
^
symbol: method doubleValue()
location: variable v of type T
where T is a type-variable:
T extends Object declared in method <T>sum(List<T>)
1 error
The compiler is right: sum could be called with a List<String>, and strings have no doubleValue() method. The error message even states the problem — T extends Object.
A bounded type parameter restricts which types may be used for T. In return, the code can use everything the bound provides:
static <T extends Number> double sum(List<T> values) // T must be Number or a subclass
Now T is known to be at least a Number, so doubleValue() is available, and calls with non-numeric types are rejected at compile time.
Upper Bounds with extends
The syntax is T extends Bound. The keyword is always extends, even when the bound is an interface (where you'd normally say "implements"):
import java.math.BigDecimal;
import java.util.*;
public class B1 {
static <T extends Number> double sum(List<T> values) {
double total = 0;
for (T v : values) total += v.doubleValue();
return total;
}
static <T extends Comparable<T>> T max(List<T> values) {
T best = values.get(0);
for (T v : values) if (v.compareTo(best) > 0) best = v;
return best;
}
static <T extends Number & Comparable<T>> T clamp(T value, T min, T max) {
if (value.compareTo(min) < 0) return min;
if (value.compareTo(max) > 0) return max;
return value;
}
public static void main(String[] args) {
System.out.println("sum ints: " + sum(List.of(10, 20, 30)));
System.out.println("sum mixed: " + sum(List.of(1.5, 2.5)));
System.out.println("sum decimal: " + sum(List.of(new BigDecimal("0.10"), new BigDecimal("0.20"))));
System.out.println("max int: " + max(List.of(42, 7, 99, 13)));
System.out.println("max string: " + max(List.of("Madurai", "Chennai", "Salem")));
System.out.println("clamp 150: " + clamp(150, 0, 100));
System.out.println("clamp 2.5: " + clamp(2.5, 1.0, 5.0));
}
}
Output:
sum ints: 60.0
sum mixed: 4.0
sum decimal: 0.30000000000000004
max int: 99
max string: Salem
clamp 150: 100
clamp 2.5: 2.5
T extends Number
sum accepts a list of any Number subtype — Integer, Double, Long, BigDecimal — and calls doubleValue(), which Number declares. Note the third result: converting the exact BigDecimal values to double brings back binary floating-point error (0.30000000000000004). A bound gives you the bound's methods; for exact decimal arithmetic you'd need a BigDecimal-specific method.
T extends Comparable<T>
max works for any type whose objects can be compared with each other: Integer (numeric order) and String (alphabetical order, so Salem is the maximum). The bound makes compareTo callable, and it also guarantees that the argument of compareTo is another T. Both results come back with their real types — Integer and String — rather than Comparable, so callers don't need casts.
Multiple bounds with &
clamp requires T to be both a Number and Comparable<T>: T extends Number & Comparable<T>. Rules for multiple bounds:
- Separate them with
&. - At most one may be a class, and if there is one, it must come first; the rest must be interfaces.
Tcan then use the methods of all its bounds.
Integer and Double satisfy both bounds, so clamp works for each, returning the same type it was given.
Violating a Bound
A bound is checked wherever the type parameter receives a value — in method calls and when creating parameterized types:
import java.util.*;
public class Violate {
static <T extends Number> double sum(List<T> values) { return 0; }
static class Stats<T extends Number> { }
public static void main(String[] args) {
sum(List.of("a", "b"));
Stats<String> s = new Stats<>();
}
}
Violate.java:9: error: method sum in class Violate cannot be applied to given types;
sum(List.of("a", "b"));
^
required: List<T>
found: List<String>
reason: inference variable E has incompatible bounds
upper bounds: Number,Object
lower bounds: String
...
Violate.java:10: error: type argument String is not within bounds of type-variable T
Stats<String> s = new Stats<>();
^
...
The important phrases are "incompatible bounds … upper bounds: Number … lower bounds: String" (the list contains Strings but T must be a Number) and "type argument String is not within bounds". Both errors are reported at compile time, in the caller's code — exactly where the mistake is.
Bounds on Classes
A class or record can bound its type parameters too. The bound then applies to every use of the class and lets all its methods rely on the bound:
class Stats<T extends Number> {
private final List<T> values = new ArrayList<>();
void add(T value) { values.add(value); }
double average() {
return values.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}
}
Stats<Integer> marks = new Stats<>(); // fine
Stats<String> names = new Stats<>(); // compile error: String is not within bounds
The Range<T extends Comparable<T>> record in the Generic Types lesson used this to compare its min and max values.
Recursive Bounds and Comparable<? super T>
T extends Comparable<T> is called a recursive bound, because T appears inside its own bound. It reads: "T can be compared with other Ts". It works for most classes, but not for all:
import java.time.*;
import java.util.*;
public class Recursive {
static <T extends Comparable<T>> T maxStrict(List<T> values) {
return Collections.max(values);
}
static <T extends Comparable<? super T>> T maxFlexible(List<T> values) {
return Collections.max(values);
}
public static void main(String[] args) {
List<LocalDate> dates = List.of(LocalDate.of(2026, 11, 1), LocalDate.of(2026, 12, 25), LocalDate.of(2026, 1, 26));
System.out.println(maxFlexible(dates));
System.out.println(maxStrict(dates));
}
}
Recursive.java:16: error: method maxStrict in class Recursive cannot be applied to given types;
System.out.println(maxStrict(dates));
^
required: List<T>
found: List<LocalDate>
reason: inference variable T has incompatible equality constraints ChronoLocalDate,LocalDate
...
Without the maxStrict line, the program prints:
2026-12-25
LocalDate doesn't implement Comparable<LocalDate>; it implements Comparable<ChronoLocalDate> — it can be compared with any date in any calendar system, a supertype of LocalDate. The strict bound demands exactly Comparable<LocalDate>, so it rejects LocalDate. The flexible bound, T extends Comparable<? super T>, means "T can be compared with T or any supertype of T", which LocalDate satisfies. The same situation arises whenever a class inherits compareTo from a parent class.
That's why the JDK's own methods use the flexible form — Collections.max is declared as <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll). The ? super syntax is a wildcard, explained in the next lesson; for now, the rule of thumb is: write <T extends Comparable<? super T>> when a generic method needs to compare Ts.
How Bounds Affect the Compiled Code
At runtime, type parameters are replaced by their bound (the Type Erasure lesson explains this in detail). An unbounded T becomes Object; T extends Number becomes Number; for multiple bounds, the first bound is used. That's one reason the class bound must come first in T extends Number & Comparable<T>: it determines the type the compiled code actually uses.
Practical Example: A Repository for Any Entity Type
Most business applications store many kinds of entities — courses, students, orders — and every entity has an ID and a last-modified timestamp. A generic repository bounded by a shared Entity interface can implement saving, lookup and change tracking once, while still returning the precise entity type to callers.
import java.time.*;
import java.util.*;
public class Repo {
interface Entity {
String id();
Instant updatedAt();
}
record Course(String id, String title, int fee, Instant updatedAt) implements Entity { }
record Student(String id, String name, Instant updatedAt) implements Entity { }
static class InMemoryRepository<T extends Entity> {
private final Map<String, T> byId = new LinkedHashMap<>();
T save(T entity) {
if (entity.id() == null || entity.id().isBlank()) {
throw new IllegalArgumentException("entity must have an id");
}
byId.put(entity.id(), entity);
return entity;
}
Optional<T> findById(String id) { return Optional.ofNullable(byId.get(id)); }
List<T> modifiedSince(Instant since) {
List<T> result = new ArrayList<>();
for (T e : byId.values()) if (e.updatedAt().isAfter(since)) result.add(e);
return result;
}
Optional<T> mostRecentlyUpdated() {
return byId.values().stream().max(Comparator.comparing(Entity::updatedAt));
}
}
public static void main(String[] args) {
Instant t = Instant.parse("2026-11-15T09:00:00Z");
InMemoryRepository<Course> courses = new InMemoryRepository<>();
courses.save(new Course("JAVA", "Java Programming", 4999, t));
courses.save(new Course("DJ", "Django Web", 5999, t.plusSeconds(3600)));
courses.save(new Course("PY", "Python Basics", 2999, t.minusSeconds(86_400)));
System.out.println("JAVA fee: " + courses.findById("JAVA").map(Course::fee).orElse(0));
System.out.println("changed since 08:00: " + courses.modifiedSince(t.minusSeconds(3600)).stream().map(Course::id).toList());
System.out.println("latest: " + courses.mostRecentlyUpdated().map(Course::title).orElse("-"));
InMemoryRepository<Student> students = new InMemoryRepository<>();
students.save(new Student("S-1", "Asha", t));
try {
students.save(new Student(" ", "Nameless", t));
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
Output:
JAVA fee: 4999
changed since 08:00: [JAVA, DJ]
latest: Django Web
rejected: entity must have an id
How the bound is used:
Entitydeclares what every entity must provide:id()andupdatedAt(). The records implement it simply by having components with those names — a record's accessor methods satisfy the interface.InMemoryRepository<T extends Entity>can therefore callentity.id()insave, ande.updatedAt()inmodifiedSince, on anyT. Without the bound, neither call would compile.- Callers still get the exact type.
courses.findById("JAVA")returnsOptional<Course>, so.map(Course::fee)works; nothing is returned as a plainEntitythat would need a cast. That's the advantage over a non-genericEntityRepositorystoringEntityobjects. Comparator.comparing(Entity::updatedAt)builds a comparator from the bound's method;maxthen finds the most recently updated course (Django, updated at 10:00).- The bound documents and enforces the contract.
new InMemoryRepository<String>()doesn't compile, becauseStringisn't anEntity.
This is the same design used by Spring Data (CrudRepository<T, ID>) and many hand-written data-access layers: shared behaviour in a generic, bounded base type; entity-specific queries in subclasses or interfaces that fix T.