Import Basics
What are Import Statements?
In Java, import statements are used to bring external classes and packages into your current source file. They allow you to use classes from other packages without specifying their fully qualified names every time.
Basic Import Syntax
The basic syntax for import statements is straightforward:
import package.subpackage.ClassName;
Types of Imports
There are three main types of import statements:
- Single Class Import
- Wildcard Import
- Static Import
Single Class Import
import java.util.ArrayList; // Imports only ArrayList class
Wildcard Import
import java.util.*; // Imports all classes in java.util package
Static Import
import static java.lang.Math.PI; // Imports static members of a class
Import Rules and Best Practices
Import Type |
Syntax |
Use Case |
Single Class |
import java.util.Date; |
When you need specific class |
Wildcard |
import java.util.*; |
When using multiple classes from same package |
Static |
import static java.lang.Math.max; |
For static method/constant access |
Common Import Scenarios
graph TD
A[Start Coding] --> B{Need External Class?}
B -->|Yes| C[Identify Package]
C --> D[Add Import Statement]
D --> E[Use Class]
B -->|No| F[Continue Coding]
Avoiding Import Conflicts
When two classes have the same name from different packages, you must use fully qualified names or explicitly import one class.
Example
java.sql.Date sqlDate; // From java.sql package
java.util.Date utilDate; // From java.util package
LabEx Tip
At LabEx, we recommend understanding import mechanisms thoroughly to write clean, efficient Java code.