Why is it better to avoid ‘*’ in import statements in Java?
Does it even matter? I have worked on a lot of Java projects and never did I once thought of this question until now. Recently, in my bootcamp at Go-jek, this question popped up and we were told to dig for the solution.
- The import directive is a compiler directive, i.e this statement is executed while compiling the code. The compiler checks for Arraylist in the same package as the class at first. If it is unable to detect a class for the same then the import directive comes into play. Now, this directive asks the compiler to search for the unidentified object in the classes which have been imported. In the first case, Arraylist will be searched in the whole util class while in the latter it can directly go and put the reference of java.util.Arraylist in the .class file. Without the wildcard(*), the directive tells the compiler to look for one specific file in the classpath. Thus, it is suffice to say that the import directive may influence the compile time but it does not affect the runtime of the program.
- Another reason that reinforces the above statement is there are many classes and interfaces with the same name in different packages.For example:
So, if you import
java.sql.* you'll have a collision on the Array type, and have to fully qualify them in your code. Importing specific classes instead will save you this hassle.
3. Suppose your code is something like-
and class Foo exists in package a. Now you check in your perfectly compiling code, and six months later, someone adds class Foo to package b. (Perhaps it’s a third party lib that added classes in the latest version).
Poof! Now your code refuses to compile.
Hence, try and refrain from the habit of using the wildcard while importing classes and enjoy the functionality provided by the your IDE(in my case- Intellij IDEA) to directly import the required classes (alt+Enter).