Good to avoid ‘*’ in import statements

So when I started with Java development, I used to get this feedback quite often during code reviews from my fellow colleagues (because of the IDE configuration :D, since as an when number of imports from same package crossed configured upper bound, IDE will replace all imports from same package with package.*) and that moment this question popped up, Does that really matter? and then have decided to dig deep and figure out the reason/impact of the same.



As the per the code block in #Sample1, blindly importing all the classes in a package clutters the class namespace and could lead to conflicts between classes in different packages with the same name. On the other hand, specifically listing the necessary classes like #Sample2, avoids that problem and makes clear which versions were wanted.



Another reason that i could find that the import statement is executed during the code compilation. The compiler checks for Date class in the same package as the class at first. If it is unable to find Date class, then the import directive comes into picture. Now, this directive asks the compiler to search for the Date class in the classes/package which have been imported.

In the #Sample4, Date will be searched in the whole util class while in the #Sample3 it can directly go and put the reference of java.util.Date in the .class file. Without the wildcard(*), the directive tells the compiler to look for one specific file in the class path. Thus, we can say that * import affect compile time but it does not affect the runtime of the implementation.


Let’s assume in #Sample5 the User class is declared in package1 only. The compiler has no issues with the code, and it runs fine.

A few months later, a developer from your team decides to add a User class to package2. Now, all of a sudden, your previously working code is failing to compile. The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you’re just doing a quick one-off thing, there’s nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store

Senior Software Engineer at Gojek | Ex-Engati Chatbot Platform | NITD