Sub topic 1
Recap: single-type and on-demand imports
Module import declarations build on the import rules Java has had since version 1.0. Most surprises in later chapters, such as ambiguous names and shadowing, come from those older rules. This chapter reviews them in detail so the later behavior is predictable.
Prerequisites
This chapter assumes you can already:
- Write, compile and run a basic Java class from the command line or an IDE.
- Read a package declaration such as
package com.example.app;and know that a class has a simple name (List) and a fully qualified name (java.util.List). - Recognize
import java.util.List;andimport java.util.*;when you see them.
You do not need to know about modules yet. The next chapter covers them.
What an import does
An import declaration is a compile-time convenience. It tells the compiler which fully qualified type a simple name refers to. It does not load a class, run code, or add a dependency to the compiled output. The compiler writes the fully qualified name into the .class file. If you replace every import with fully qualified names, you get the same bytecode.
Two consequences follow:
- An unused import costs nothing at runtime. It can still trigger a compile error if the imported type does not exist.
- Imports cannot make an inaccessible type usable. A package-private class in another package stays unreachable no matter what you import.
The four kinds of import declaration
Java has four import forms. Two work on types and two on static members.
| Form | Example | What it makes available by simple name |
|---|---|---|
| Single-type import | `import java.util.List;` | That one type |
| Type-import-on-demand | `import java.util.*;` | All accessible types in the package |
| Single-static import | `import static java.lang.Math.max;` | All static members named `max` of that type |
| Static-import-on-demand | `import static java.lang.Math.*;` | All accessible static members of that type |
The wildcard form is called "on demand" because the compiler looks into the package only when it meets a simple name it cannot resolve another way.
Single-type imports
A single-type import names exactly one type. It is the most explicit form. Anyone reading the file can see where each type comes from.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SingleTypeDemo {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan");
Map<String, Integer> lengths = new HashMap<>();
for (String name : names) {
lengths.put(name, name.length());
}
String joined = names.stream()
.sorted()
.collect(java.util.stream.Collectors.joining(", "));
System.out.println(joined);
System.out.println(lengths.get("Grace"));
}
}Collectors is not imported here, so the code writes its fully qualified name, java.util.stream.Collectors. A fully qualified name always works without any import.
Some details of single-type imports:
- The imported type must exist and be accessible. A misspelled name is a compile error at the import line.
- Importing the same type twice is allowed. The second declaration is redundant and ignored.
- Importing two different types with the same simple name is an error at the import line, even if you never use the name.
- You can import a nested type with its canonical name, for example
import java.util.Map.Entry;. ThenEntrycan be used alone.
Type-import-on-demand
An on-demand import uses an asterisk and brings in every accessible type of one package.
import java.util.*;
import java.util.stream.*;
public class OnDemandDemo {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan");
Map<String, Integer> lengths = new HashMap<>();
for (String name : names) {
lengths.put(name, name.length());
}
String joined = names.stream()
.sorted()
.collect(Collectors.joining(", "));
System.out.println(joined);
System.out.println(lengths.get("Grace"));
}
}This does the same work as the previous example with two lines instead of three imports plus a fully qualified name. Note the second line. java.util.* does not cover java.util.stream.
Wildcards do not reach into subpackages
Packages look hierarchical, but the hierarchy is only in the names. java.util and java.util.stream are unrelated packages as far as imports are concerned. Each one needs its own declaration. This is the most common wildcard mistake. The wildcard also cannot appear anywhere except the end, so import java.*.List; is invalid.
Only accessible types are imported
A wildcard import covers types that are accessible from your code. For a package in a different package from yours, that means public types. Package-private helper classes in java.util are not made visible. Importing on demand never exposes more than you could already name with a fully qualified name.
Member types on demand
The on-demand form also works on a type. import java.util.Map.*; imports the member types of Map, such as Entry. Do not confuse it with import static java.util.Map.*;, which imports static members.
Static imports
Static imports let you call static methods and use static fields without the class name.
import static java.lang.Math.max;
import static java.util.stream.Collectors.joining;
import java.util.List;
public class StaticImportDemo {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace", "Alan");
System.out.println(max(3, 7));
System.out.println(names.stream().collect(joining("-")));
}
}import static java.lang.Math.max; imports every static member named max, so all overloads of max come along. The static on-demand form import static java.lang.Math.*; imports all accessible static members. Static member types are included in both forms.
Static imports follow the same ideas as type imports: single forms are explicit and win over on-demand forms. Use them sparingly. Names like max or joining are readable only when their origin is obvious.
The implicit import of java.lang
Every compilation unit behaves as if it began with import java.lang.*;. This is why String, Object, Math and Integer need no import. It is an ordinary on-demand import, so it follows the same rules, including that it can be shadowed. A single-type import or a type in your own package named Record or Object hides the java.lang one. Later chapters return to this idea, because a module import for java.base behaves in the same family.
Which declaration wins
When one simple name could mean several things, the compiler resolves it by scope and shadowing. For types, the order from strongest to weakest is:
- Types declared in the same compilation unit, and types brought in by single-type imports. These two groups cannot conflict with each other. A single-type import of a different type with the same simple name as a type declared in the file is an error.
- Other types in the same package, from other source files.
- Types brought in by on-demand imports, including the implicit
java.lang.*.
Inner scopes also matter. A type parameter, local class, or member type inherited by the class you are writing shadows all of the above inside its own scope. The flowchart shows the file-level lookup.
The table gives concrete cases:
| Situation | Result |
|---|---|
| `import java.util.*;` and your package has its own `List` class | Your `List` wins. The on-demand import is shadowed |
| `import java.util.List;` and your package has its own `List` class | `java.util.List` wins. A single-type import shadows same-package types |
| `import java.util.*;` and `import java.sql.*;`, then use `Date` | Compile error: ambiguous |
| `import java.util.*;`, `import java.sql.*;` and `import java.util.Date;` | `java.util.Date`. The single-type import wins |
| `import java.util.Date;` and `import java.sql.Date;` | Compile error at the second import |
| Top-level `class Date` in the file and `import java.util.Date;` | Compile error. The two clash |
Ambiguity between on-demand imports
When two wildcard imports supply the same simple name, nothing goes wrong until you use that name. The error is reported at the use, not at the import.
import java.sql.*;
import java.util.*;
public class AmbiguousOnDemand {
public static void main(String[] args) {
// Date d = null;
// error: reference to Date is ambiguous,
// both class java.sql.Date in java.sql and
// class java.util.Date in java.util match
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(sqlDate);
}
}This program compiles because the ambiguous simple name appears only in a comment. It runs on a standard JDK because java.sql ships with it. There are two fixes:
- Use fully qualified names where you need the clash name, as above.
- Add a single-type import for the one you want, as in the next example.
import java.sql.*;
import java.util.*;
import java.util.Date;
public class ResolvedDate {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.getTime() > 0);
}
}The single-type import shadows the on-demand imports for that one name. Other java.sql types, such as Timestamp, still work by simple name. If you need both Date types in one file, import one and write the other fully qualified.
Style conventions and trade-offs
Teams settle this question differently, so know the arguments for each side.
Arguments for single-type imports:
- Every name has a visible origin, which helps in code review and when you read code outside an IDE.
- They are immune to new types appearing in an imported package.
- They make dependency changes visible in version control diffs.
Arguments for on-demand imports:
- Shorter import lists, and less churn when a file uses one more type from the same package.
- Quick for small programs, examples and scripts.
Many style guides require single-type imports in production code. Many IDEs switch to a wildcard automatically after a threshold, often five or ten imports from one package. Static on-demand imports are usually discouraged outside tests, where import static org.junit.jupiter.api.Assertions.*; is common.
Common errors
- "cannot find symbol" after a wildcard import. You expected
java.util.*to coverjava.util.concurrent. Add a separate import. - "reference to X is ambiguous." Two on-demand imports supply
X. Add a single-type import or qualify the name. - "a type with the same simple name X is already defined by the single-type-import." Two single-type imports collide, or a type in the file collides with an import. Remove one or use a qualified name.
- The wrong class gets picked silently. A class in your own package has the same simple name as a type imported on demand. The local class wins without any warning.
- Importing a package that does not exist.
import java.utils.*;is an error. A misspelled on-demand import is reported at the import line.
Why this recap matters for module imports
A module import declaration, covered in the following chapters, is a third kind of on-demand import. It imports the types of every package that a module exports, with one line. The precedence rules are the ones above, extended with one more level. The ambiguity rule is the same: a clash is reported only when you use the name. Keep this chapter's precedence list in mind, because it is the baseline.
Exercise
A file in package shop has import java.util.*;, and package shop also contains a class named List in another file. The file uses List<String> and the code fails because List has no type parameters. Why does this happen, and what is the smallest change that makes java.util.List the meaning?
Show answer
A type in the same package shadows a type imported on demand, so List refers to shop.List. Adding the single-type import import java.util.List; fixes it, because a single-type import shadows same-package types. Writing java.util.List<String> at the use site also works.
Exercise
Which of these lines compile, given only import java.util.*; at the top of the file? (a) List<String> a = new ArrayList<>(); (b) Stream<String> s = a.stream(); (c) String t = "x";
Show answer
(a) compiles because List and ArrayList are in java.util. (b) does not compile because Stream is in java.util.stream, and a wildcard does not import subpackages. (c) compiles because String comes from the implicit java.lang.* import.