1. The Hook (The "Byte-Sized" Intro)
In a Nutshell: The import statement allows you to use classes from other packages without typing the full name every time. import java.util.ArrayList; lets you write ArrayList instead of java.util.ArrayList. Java also supports static imports for importing static members directly.
Think of contacts in your phone. Instead of dialing "+1-555-123-4567" (fully qualified name), you import the contact as "Mom" (simple name)!
2. Conceptual Clarity (The "Simple" Tier)
💡 The Analogy: The Shortcut
- Full path:
/Users/john/Documents/Work/Project/file.pdf - Alias/Import: "work-file" (shortcut)
Imports create shortcuts to classes!
3. Technical Mastery (The "Deep Dive")
Import Types
- Single-type:
import java.util.ArrayList; - On-demand:
import java.util.*;(all classes in package) - Static import:
import static java.lang.Math.PI;
Rules
java.lang.*is automatically imported- Imports come after package, before class
*imports classes, not subpackages
4. Interactive & Applied Code
package com.myapp;
// Single-type imports (preferred)
import java.util.ArrayList;
import java.util.HashMap;
// On-demand import (use sparingly)
import java.io.*;
// Static import
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(); // No java.util needed!
double area = PI * 5 * 5; // No Math.PI needed!
double root = sqrt(16); // No Math.sqrt needed!
// Fully qualified name (no import)
java.util.Date date = new java.util.Date();
}
}5. The Comparison & Decision Layer
| Import Type | Example | When to Use |
|---|---|---|
| Single-type | import java.util.List; | Preferred (explicit) |
| On-demand | import java.util.*; | Quick prototyping |
| Static | import static Math.PI; | Constants/utilities |
6. The "Interview Corner" (The Edge)
The "Killer" Interview Question:
"What's the difference between import java.util.* and import java.util.regex.*;?"
Answer: * imports classes in that package only, NOT subpackages! So import java.util.*; does NOT import java.util.regex.Pattern. You need a separate import!
Pro-Tip: Avoid import * in production:
- Makes dependencies unclear
- Can cause name conflicts
- Harder to track unused imports
IDEs auto-organize imports—use them!