Course contentsShow
← Java
Lesson 678 of 2,87016. Packages, Imports, and JAR FilesFree lesson

When to Use FQNs vs Import Statements

Learn trade-offs between typing FQNs inline versus using import declarations.

When to Use FQNs vs Import Statements

You'll learn: How to decide whether to type out fully qualified names or add import declarations at the top of your file.

Now that you understand both fully qualified names (FQNs) and import statements, it's time to learn when to use each approach. This is a practical trade-off that affects code readability and maintainability.

The General Rule: Prefer Imports

For classes you use frequently in a file, import statements are the standard choice. They eliminate clutter and make your code easier to read:

import java.util.ArrayList;
import java.util.HashMap;

public class DataProcessor {
    private ArrayList<String> names;  // Clean and readable
    private HashMap<String, Integer> scores;
}

Writing ArrayList repeatedly is much cleaner than java.util.ArrayList everywhere.

When to Use FQNs Instead

Use fully qualified names in these specific situations:

  1. Name Conflicts: When two classes have the same simple name (e.g., java.util.Date and java.sql.Date), use FQNs for at least one to avoid ambiguity.

  2. One-Time Use: If you only reference a class once or twice in a large file, typing the FQN inline can be clearer than adding an import for a single occurrence.

  3. Emphasizing Origin: Sometimes the package name adds important context. For example, javax.swing.Timer vs java.util.Timer makes the distinction obvious.

Analogy: Imports are like introducing someone at a party: "This is Sarah." After that, you just say "Sarah." But if two Sarahs arrive, you'll use "Sarah from accounting" and "Sarah from marketing" to avoid confusion.

Key Takeaway:
Prefer import statements for frequently used classes to keep code clean; use FQNs to resolve name conflicts, for single-use classes, or when the package name adds important clarity.