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

Import Precedence and Handling Name Conflicts

Discover how Java resolves conflicts when multiple packages contain classes with the same name, and why explicit imports matter.

Import Precedence and Handling Name Conflicts

What you'll learn: How Java resolves ambiguity when multiple packages contain classes with the same name.

The Problem: Name Collisions

Imagine two different companies both create a Date class—one in java.util and another in java.sql. If you import both packages using wildcards, Java needs rules to determine which Date you mean when you write code.

How Java Resolves Conflicts

Java follows a strict precedence order:

  1. Explicit class name in your code wins: If you write the fully qualified name (java.util.Date), Java uses exactly that class.

  2. Single-type imports beat wildcard imports: A specific import java.util.Date; takes precedence over import java.sql.*;

  3. Wildcard conflicts cause compile errors: If you have import java.util.*; and import java.sql.*; without a single-type import, using Date without qualification triggers a compiler error—you must clarify which one you mean.

Practical Solutions

Option 1: Use a single-type import for the class you'll use most:

import java.util.Date;  // This Date is now your default
import java.sql.*;

Option 2: Use fully qualified names when you need the "other" class:

java.sql.Date sqlDate = new java.sql.Date(System.currentTimeMillis());

Option 3: Avoid wildcard imports entirely and be explicit about every import.

Why This Matters

Without these rules, your code would be ambiguous and unpredictable. Java forces you to be explicit when conflicts arise, preventing subtle bugs where the wrong class is accidentally used.

Key Takeaway: Java resolves import conflicts by prioritizing explicit single-type imports over wildcards; when ambiguity remains, the compiler forces you to use fully qualified names to clarify your intent.