Sub topic 8
Wildcard imports and their trade-offs
This chapter assumes you can write and compile a multi-class Java program and that you know how a package declaration and a single-type import work. Here you will learn what a wildcard import does, how the compiler uses it to resolve names, and when to avoid it.
What a wildcard import is
A wildcard import, also called an on-demand import, makes every accessible type in one package available by its simple name:
import java.util.*;After this line, List, ArrayList, Map and every other public type in java.util can be written without the java.util. prefix. The * stands for types only. It does not mean "everything under this name".
The wildcard has four properties that are easy to get wrong.
- It is not recursive.
import java.util.*;does not importjava.util.concurrent.ExecutorService. Subpackages are separate packages, so you needimport java.util.concurrent.*;as well. - It costs nothing at run time. An import is a compile-time instruction. It does not load classes, and the compiled
.classfile records only the types your code uses. Importingjava.util.*is as fast to run as importing three classes. - It covers only accessible types. Package-private types in the imported package are skipped. This matters when you wildcard-import one of your own packages from another one.
- It does not import static members. For those you need
import static java.lang.Math.*;, which is the static on-demand form from the previous chapter.
You can also write a wildcard over the nested types of a class. import java.util.Map.*; makes Entry available as a simple name. Wildcards cannot be chained, so import java.*.*; is a syntax error. import java.*; is legal but useless, because the package java contains no types of its own.
How the compiler resolves a simple name
When the compiler meets a simple name such as Date, it checks several scopes in a fixed order and stops at the first match. This order explains almost every surprise with wildcards.
| Order | Scope | Example |
|---|---|---|
| 1 | Types declared in the current file, and member types visible there | a nested `class Date` in your file |
| 2 | Single-type imports | `import java.sql.Date;` |
| 3 | Types in the same package (all files) | `com.example.shop.Date` |
| 4 | On-demand imports, including the implicit `java.lang.*` | `import java.util.*;` |
Wildcard imports sit at the bottom. A name found at a higher level hides any same-named type at a lower level, without an error or a warning.
Ambiguity: two wildcards, one name
Both java.util and java.sql contain a class named Date. If you wildcard-import both and use the simple name, the compiler cannot choose:
import java.util.*;
import java.sql.*;
public class AmbiguousDate {
public static void main(String[] args) {
Date d = new Date();
System.out.println(d);
}
}This fails with an error like reference to Date is ambiguous, both class java.sql.Date in java.sql and class java.util.Date in java.util match.
Two details matter here.
- The error appears only where the ambiguous name is used. Having both imports is legal. A file that never writes
Datecompiles without complaint. - The fix is to move one name up the table. A single-type import wins over any wildcard:
import java.util.*;
import java.sql.Date;
public class ResolvedDate {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Pen");
Date d = new Date(0L);
System.out.println(names + " " + d.getClass().getName());
}
}This prints [Pen] java.sql.Date. List and ArrayList still come from the wildcard, and Date comes from the explicit import. If you need both Date classes in one file, import neither by single-type and write at least one with its fully qualified name, as shown in the earlier chapter on name conflicts.
Silent shadowing by your own package
Because the same package ranks above wildcards, a class in your own package hides a wildcard-imported class of the same name. Suppose com.example.shop contains its own class List, a custom shopping list:
package com.example.shop;
import java.util.*;
public class Cart {
private List<String> items = new ArrayList<>();
}Here List refers to com.example.shop.List, not java.util.List. If your List is not generic, you get a confusing error about type arguments. Nothing says the import was ignored.
The same happens over time. Imagine a library adds a new type named Item to a package you wildcard-import, while you already have com.example.shop.Item. Your class still wins, so the code compiles unchanged. The reverse is the dangerous case. If a second wildcard-imported package gains a type with a name you already use from the first, previously working code starts failing with "ambiguous". The JDK has added classes between releases, for example java.util.HexFormat in Java 17. Code that wildcard-imports java.util.* along with another package that has its own HexFormat would fail to compile after upgrading.
The implicit wildcard: java.lang
Every compilation unit behaves as if it began with import java.lang.*;. That is why String, Math and Thread need no import. It is an on-demand import, so it is last in the order. Your own class named String or Record in the same package would hide the java.lang one. That is legal, and almost always a mistake.
Readability and tooling
Wildcards are shorter, but they hide where each name comes from. A reader who sees Parser in a file with six wildcard imports has to search to find it. Single-type imports make each dependency visible at the top of the file. This also helps in code review, in diffs, and when you run grep for usages of a class.
Style guides differ.
- The Google Java Style Guide forbids wildcard imports, static or otherwise.
- Many teams allow them only for very large sets of related names, such as
java.util.*in a short script or test. - IntelliJ IDEA collapses imports into a wildcard automatically once you use five or more classes from one package (three or more for static imports). You can change this under the code style settings. Eclipse and VS Code have similar options.
If your project has a formatter or a checkstyle rule, follow it. When it does not, a good default is to use single-type imports and let the IDE manage them.
Choosing between the forms
| Situation | Preferred form |
|---|---|
| Normal production code | Single-type imports |
| Two packages share a class name you need | Single-type import for one, fully qualified name for the other |
| Quick demo, scratch file or exam answer | `import java.util.*;` is acceptable |
| A static helper used heavily in a test class | A static import of the specific members |
| Generated code | Whatever the generator emits |
Common errors
- Expecting
import java.util.*;to coverjava.util.functionorjava.util.stream. You getcannot find symbolforFunctionorStream. Import each package separately. - Importing two wildcards that overlap and never noticing. The error appears only when a clashing name is first used. Adding code that uses
DateorListcan suddenly break a file. - Assuming a wildcard slows startup. It does not. Only classes your code uses are loaded, and only when needed.
- Adding a wildcard to cure
cannot find symbolfor a class in a different package. The wildcard must name that exact package. Check the package of the class first. - Trying to wildcard-import from the default package. This is not possible, which is one reason to avoid the default package.
Exercise
A file begins with import java.util.*; and import java.awt.*;. It declares List<String> names = new ArrayList<>();. Does it compile? If not, give two different ways to fix it without removing either wildcard.
Show answer
It does not compile. Both java.util and java.awt contain a class named List, so the simple name List is ambiguous and the compiler reports it at that line. Fix 1: add the single-type import import java.util.List;, which beats both wildcards. Fix 2: write the fully qualified name java.util.List<String> names = new ArrayList<>();. ArrayList is not affected, because only java.util has it.
Exercise
The package com.example.shop contains a class Item. A file in that package has import com.example.catalog.*;, and com.example.catalog also has a class Item. Which Item does the file's simple name Item refer to, and why?
Show answer
It refers to com.example.shop.Item. A type in the same package is checked before on-demand imports, so it hides the wildcard-imported com.example.catalog.Item without any error or warning. To use the catalog class, import it with a single-type import (import com.example.catalog.Item;), which outranks the same package, or write its fully qualified name.