Imports &
Qualified Names
Master how Java organizes classes into packages, and learn the two ways to reference them: import statements and fully qualified names.
What Is a Package?
A package is a namespace that groups related Java classes and interfaces. Think of it as a folder system for your code: it prevents naming conflicts and keeps large projects organized.
Why Do We Need Imports?
The Java standard library contains thousands of classes across hundreds of packages. Without imports, you would need to type the full address of every class each time you use it.
The java.lang Exception
One package is always imported automatically: java.lang. That is why you can use String, Math, System, and Integer without writing any import statement.
The import Statement
Wildcard * Imports
You can import all classes in a package at once using the asterisk wildcard. This does not import sub-packages.
Fully Qualified Names
Instead of importing, you can use a class's full address directly in your code. This is called a fully qualified name (FQN).
import vs Fully Qualified Name
| import Statement | Fully Qualified Name | |
|---|---|---|
| Location | Top of the file | Inline, wherever class is used |
| Scope | Whole file | Single usage point |
| Readability | Clean, short names | Verbose, long paths |
| Name conflicts | Can cause ambiguity | Resolves ambiguity |
| Typical use | Day-to-day coding | Resolving naming collisions |
Resolving Name Conflicts
Both java.util and java.sql contain a class called Date. If you import both with wildcards, the compiler cannot tell which Date you mean.
Step-by-Step Checklist
Example 1: Single Import
Write a program that reads a number from the user and prints its square.
Example 2: Multiple Imports
Store names in a list and write them to a file.
Example 3: Name Collision
Use both java.util.Date and java.sql.Date in the same file.
File Layout Order
Common Mistakes
Question 1 of 5
Which import statement correctly allows you to use ArrayList in your code?
Question 2 of 5
Which package is automatically imported into every Java file?
Question 3 of 5
What does import java.util.*; import?
Question 4 of 5
You need both java.util.Date and java.sql.Date in the same file. What is the best approach?
Question 5 of 5
Consider the following code:
import java.util.*;
import java.sql.*;
public class Test {
public static void main(String[] args) {
Date d = new Date();
}
}
What happens when you try to compile this code?