Java Wildcards

Introduction

Java Generics provide compile-time type safety and make code more reusable. However, there are situations where you want a generic method or class to work with multiple related generic types instead of one specific type. For example, you may want a method that accepts a List<Integer>, List<Double>, or List<String> without writing separate methods for each type.

This is where Java Wildcards come into play.

A Wildcard is represented by the question mark (?) symbol and is used with Generics to represent an unknown type. Wildcards make generic code more flexible by allowing methods and APIs to operate on different generic types while still maintaining type safety.

Java provides three types of wildcards:

  • Unbounded Wildcards (<?>)
  • Upper Bounded Wildcards (<? extends Type>)
  • Lower Bounded Wildcards (<? super Type>)

What are Java Wildcards?

A Wildcard is a special symbol (?) used with Java Generics to represent an unknown type.

Instead of specifying an exact generic type, a wildcard allows a method or variable to work with different generic types.

For example:


List<?> list;

The variable list can refer to:

  • List<String>
  • List<Integer>
  • List<Double>
  • List<Employee>
  • Any other generic list

The exact type is unknown, which is why the ? symbol is called a wildcard.

Why Use Wildcards?

Wildcards provide several benefits:

  • Increase code flexibility
  • Improve API design
  • Reduce duplicate methods
  • Support reusable algorithms
  • Work with multiple generic types
  • Maintain compile-time type safety
  • Simplify collection processing

Without wildcards, developers often need to overload methods for different generic types.

Syntax of Wildcards

Java supports three wildcard forms:

Unbounded Wildcard


List<?> list;

Upper Bounded Wildcard


List<? extends Number> list;

Lower Bounded Wildcard


List<? super Integer> list;

Each wildcard serves a different purpose.

Unbounded Wildcard (<?>)

An Unbounded Wildcard represents any data type.

Example


import java.util.*;
public class Main {
    public static void printList(
            List<?> list) {
        for (Object item : list) {
            System.out.println(item);
        }
    }
    public static void main(String[] args) {
        List<String> names =
                Arrays.asList(
                        "Java",
                        "Python");
        List<Integer> numbers =
                Arrays.asList(
                        10, 20, 30);
        printList(names);
        printList(numbers);
    }
}

Output

Java
Python
10
20
30

The same method works for lists of different types.

Characteristics

  • Accepts any generic type.
  • Suitable for reading values.
  • New elements (except null) cannot be added safely because the exact type is unknown.

Upper Bounded Wildcard (<? extends Type>)

An upper bounded wildcard restricts the allowable types to a specified class or its subclasses.

Example


import java.util.*;
public class Main {
    public static double sum(
            List<? extends Number> list) {
        double total = 0;
        for (Number num : list) {
            total += num.doubleValue();
        }
        return total;
    }
    public static void main(String[] args) {
        List<Integer> integers =
                Arrays.asList(10, 20, 30);
        List<Double> doubles =
                Arrays.asList(2.5, 3.5);
        System.out.println(sum(integers));
        System.out.println(sum(doubles));
    }
}

Output

60.0
6.0

The method accepts:

  • Integer
  • Double
  • Float
  • Long
  • Any subclass of Number

Characteristics

  • Ideal for reading data.
  • Prevents adding new elements (except null).
  • Ensures all elements are at least of the specified upper bound.

Lower Bounded Wildcard (<? super Type>)

A lower bounded wildcard allows the specified type and its superclasses.

Example


import java.util.*;
public class Main {
    public static void addNumbers(
            List<? super Integer> list) {
        list.add(100);
        list.add(200);
    }
    public static void main(String[] args) {
        List<Number> numbers =
                new ArrayList<>();
        addNumbers(numbers);
        System.out.println(numbers);
    }
}

Output

[100, 200]

The method accepts:

  • Integer
  • Number
  • Object

Characteristics

  • Suitable for writing data.
  • Reading returns Object because the exact type is not known.

Wildcards vs Type Parameters

Wildcards (?) Type Parameters ()
Represent an unknown type Represent a named type parameter
Commonly used in method parameters Used in generic classes and methods
Increase flexibility Define reusable generic types
Ideal when the exact type is not important Ideal when the same type is used multiple times

Use wildcards when the method does not need to know the exact type.

The PECS Principle

A common guideline for choosing wildcards is PECS:


Producer Extends, Consumer Super

Producer (extends)

If a collection only produces data (you read from it):


List<? extends Number>

Use extends.

Consumer (super)

If a collection consumes data (you add to it):


List<? super Integer>

Use super.

This rule helps you choose the correct wildcard for a given situation.

Real-Life Example

Suppose an educational application calculates the average marks of students.


import java.util.*;
public class Main {
    public static double average(
            List<? extends Number> marks) {
        double total = 0;
        for(Number mark : marks) {
            total += mark.doubleValue();
        }
        return total / marks.size();
    }
    public static void main(String[] args) {
        List<Integer> math =
                Arrays.asList(
                        80, 90, 85);
        List<Double> science =
                Arrays.asList(
                        88.5, 91.0, 86.5);
        System.out.println(
                average(math)
        );
        System.out.println(
                average(science)
        );
    }
}

Output

85.0
88.67

The same method works with different numeric types without duplication.

Advantages of Wildcards

  • Increase flexibility
  • Reduce duplicate methods
  • Improve API design
  • Support reusable algorithms
  • Maintain compile-time type safety
  • Work seamlessly with collections
  • Improve code readability

Common Mistakes

1. Confusing Wildcards with Type Parameters

Wildcards (?) represent unknown types, while type parameters (<T>) define named generic types.

2. Using extends When Adding Elements

Incorrect:


List<? extends Number> list;

You cannot safely add elements (other than null) because the actual subtype is unknown.

3. Using super When Reading Specific Types

Reading from a List<? super Integer> returns Object, not Integer.

4. Overusing Wildcards

Do not use wildcards if a regular type parameter provides a clearer solution.

5. Ignoring the PECS Rule

Remember:

  • Producer → extends
  • Consumer → super

Choosing the wrong wildcard can make APIs restrictive or unsafe.

Best Practices

📖
Best Practices:
  • Use <?> when the exact type is irrelevant.
  • Use <? extends T> for read-only collections.
  • Use <? super T> for write-only collections.
  • Follow the PECS principle.
  • Avoid unnecessary wildcard complexity.
  • Prefer readability over clever generic code.
  • Use meaningful documentation for public APIs.

Conclusion

Java Wildcards are an essential part of the Generics system, allowing methods and APIs to work with different generic types while maintaining compile-time type safety. By using the ? symbol, developers can create flexible code that handles unknown types efficiently.

Understanding the differences between unbounded (<?>), upper bounded (<? extends T>), and lower bounded (<? super T>) wildcards, along with the PECS principle, helps you design robust and reusable APIs. Mastering wildcards is particularly important when working with the Java Collections Framework, utility libraries, and enterprise applications, making them a key topic for both professional Java development and technical interviews.

Related Java Tutorials