Java Bounded Types

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 162 of 306

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.
  • T can 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:

  1. Entity declares what every entity must provide: id() and updatedAt(). The records implement it simply by having components with those names — a record's accessor methods satisfy the interface.
  2. InMemoryRepository<T extends Entity> can therefore call entity.id() in save, and e.updatedAt() in modifiedSince, on any T. Without the bound, neither call would compile.
  3. Callers still get the exact type. courses.findById("JAVA") returns Optional<Course>, so .map(Course::fee) works; nothing is returned as a plain Entity that would need a cast. That's the advantage over a non-generic EntityRepository storing Entity objects.
  4. Comparator.comparing(Entity::updatedAt) builds a comparator from the bound's method; max then finds the most recently updated course (Django, updated at 10:00).
  5. The bound documents and enforces the contract. new InMemoryRepository<String>() doesn't compile, because String isn't an Entity.

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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Bounded Types and get answers drawn from it.

Signed-in readers only.