Import Basics
What is Import in Java?
In Java, the import
statement allows you to use classes and interfaces defined in other packages without specifying their fully qualified names every time. It provides a way to organize and modularize code by grouping related classes together.
Basic Import Syntax
There are two primary ways to import classes in Java:
- Importing a specific class
import java.util.ArrayList;
- Importing an entire package
import java.util.*;
Import Types
Single Class Import
When you want to use a specific class from a package:
import java.time.LocalDate;
public class DateExample {
LocalDate today = LocalDate.now();
}
Wildcard Import
When you need multiple classes from the same package:
import java.util.*;
public class CollectionExample {
ArrayList<String> list = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
}
Import Rules and Best Practices
Import Type |
Syntax |
Recommendation |
Specific Class |
import java.util.ArrayList; |
Preferred for clarity |
Wildcard |
import java.util.*; |
Use sparingly |
Fully Qualified Name |
java.util.ArrayList list; |
Least recommended |
Package Structure in Java
graph TD
A[Java Package Structure] --> B[java.lang]
A --> C[java.util]
A --> D[java.time]
A --> E[java.io]
Common Import Scenarios
- Standard library classes
- Third-party library classes
- Your own custom package classes
Resolving Import Conflicts
When two packages have classes with the same name, you must use the fully qualified name:
java.util.Date utilDate;
java.sql.Date sqlDate;
LabEx Learning Tip
When learning Java imports, practice is key. LabEx provides interactive environments to help you master import concepts and package management.