Pitfalls of import wildcards in Java

What does the import statement do?

Import statements tell the Java compiler which packages contain the classes you use in your application.   

Tip: All classes in the java.lang package are imported automatically

How do I use the import statement?

You can import a single class:

import java.util.Date;

Or all the classes in a package:

import java.util.*;

There's no performance impact to using the wildcard since the compiler will only import the classes required by your code.   

Why can the wildcard cause problems?

Consider the situation below:

import java.util.*;
import java.sql.*;

public class Movie {
   Date releaseDate;  // DOESN'T COMPILE
   public static void main (String[] args) { }

The compiler will complain with an error saying "The type Date is ambiguous".   This is because of a namespace collision.  The Date class is declared in both java.util.Date and java.sql.Date, and the compiler does not know which one you want.

Now, let's consider this code which compiles successfully today:

import com.company.packageA.*;
import com.company.packageB.*;

public class Record {
   User user; 
   public static void main (String[] args) { }

Let's assume the User class is declared in packageA only.   The compiler has no issues with the code, and it runs fine. 

A few months later, a developer from your company decides to add a User class to packageB.  Now, all of a sudden, your previously working code is failing to compile.   

Using explicit imports avoids this issue and increases code clarity.   A developer reading your code will know exactly which classes you are importing. 

If you're using Eclipse, you can hit Ctrl+Shift+O to automatically add the necessary import statements to your source file.

There's even a section in the Google Java Style Guide about avoiding wildcard imports.