The import Statement: Simplifying Fully Qualified Names
What you'll learn: How to use import statements to write shorter, cleaner code by avoiding repetitive fully qualified class names.
The Problem with Fully Qualified Names
In the previous lessons, you learned that every class in a package has a fully qualified name like com.example.utils.StringHelper. While using these full names ensures clarity about which class you're using, typing them repeatedly throughout your code becomes tedious and clutters your source files.
Imagine writing com.example.utils.StringHelper every single time you need to reference that class—your code would quickly become unreadable!
The Solution: import Statements
The import statement acts like a shortcut or abbreviation system. You declare once at the top of your file which classes you'll be using, and then Java lets you refer to them by their simple names throughout the rest of your code.
Think of it like contact names in your phone: Instead of dialing the full number every time, you save "Mom" once and then just tap "Mom" whenever you need to call.
Syntax
Place import statements after your package declaration but before your class declaration:
package com.myapp.main;
import com.example.utils.StringHelper;
import java.util.ArrayList;
public class MyProgram {
public static void main(String[] args) {
StringHelper helper = new StringHelper(); // Short name!
ArrayList<String> list = new ArrayList<>(); // No java.util prefix needed
}
}
Without imports, you'd need to write com.example.utils.StringHelper and java.util.ArrayList every time.
Key Takeaway: The import statement lets you use a class's simple name throughout your code instead of writing its fully qualified name repeatedly, making your code cleaner and more readable.