Single-Type Import Declarations
What you'll learn: How to import a specific class from a package to use its simple name without the full package path.
When you work with classes from other packages, you can always use their fully qualified names (like java.util.ArrayList), but that gets tedious quickly. Single-type import declarations let you bring one specific class into your source file so you can refer to it by its simple name alone.
The Syntax
A single-type import declaration looks like this:
import java.util.ArrayList;
You place this statement at the top of your source file, after the package declaration (if any) and before any class declarations. The keyword import is followed by the fully qualified name of exactly one class.
How It Works
Once you've imported java.util.ArrayList, you can write:
ArrayList<String> list = new ArrayList<>();
Instead of:
java.util.ArrayList<String> list = new java.util.ArrayList<>();
Think of it like adding a shortcut to your phone's contacts: instead of typing the full phone number every time, you just tap the name.
Multiple Single-Type Imports
You can import multiple classes, each with its own import statement:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
Each import brings in exactly one class, making your code cleaner and your intentions crystal clear.
Why Use Single-Type Imports?
Single-type imports improve code readability, make dependencies explicit, and avoid namespace pollution. You know exactly which classes your code relies on just by reading the import section.
Key Takeaway: Use single-type import declarations (like import java.util.ArrayList;) to reference specific classes by their simple names, making your code cleaner without sacrificing clarity.