For instance when you work in a team at the same file and have only a partial understanding of the different packages imported needed for the code to work. You change some code in this file and find out some code become redundant because of that. You delete that part and now do not know if the whole code still depends on all packages or not.
[Of course bad can be objectified in many ways: speed, read-abilty etc.]
Yes. For a couple of reasons:
For these reasons, java will emit warnings if an import statement isn't needed and IDEs have ways to automatically delete unused imports.
Note, I didn't mention speed or performance changes, I think javac is smart enough to know not to use any unneeded imports so the compiled class will be just as if you didn't import it.
You should always only use as few of the imports as necessary, and don't use complete package imports like java.util.*
. Today's IDE's usually support this with an "Organize Imports" operation during which unused imports are removed.
If you have bunch of unused imports and you modify the code, there is a chance you will add/change code that refers to classes which are covered by the unused imports. Then you won't notice that you accidentally utilized them even though that might not be your intent.
If you only have the minimum imports, if you add code that refers to a new class, the compiler will immediately notify you by showing errors, and giving you the possibility to choose which class you intend to use.
Also if you use imports beyond what is currently referenced in your program, you increase the chance to break your program for future releases of Java or the libraries you use.
Example: If your program only uses java.util.HashSet
but you still import java.util.*
and you use another 3rd party library from where you import com.mylib.*
, your code might compile. If in a future release the 3rd party library adds a class named com.mylib.HashSet
, you're code might not compile anymore because the compiler might not be able to tell which class you wanted to use (e.g. java.util.HashSet
or com.mylib.HashSet
).
Have you imported only java.util.HashSet
only and e.g. com.mylib.SomeUtil
in the first place, your code would still compile with the new version of the 3rd party lib.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With