Closer Look into imports In Java
Java| Perfomance|Good Practice|Coding Style|Tooling
Before diving into imports let’s start with a package. It is a way to organize classes, meanwhile providing them a separate namespace and structure projects in a better way. Import statements are used to access the class files from these packages.import keyword is used to import packages.
Do imports affect performance?
There is a misconception like unused imports affect the performance of the code. They won’t affect the performance of the application in any way. But in some cases, this may cause conflicts between classes in the namespace.
So it’s advised to avoid or remove unused imports from the code to improve readability and to avoid class conflicts.
Do imports have something to do with class loading?
Don’t confuse the word import with class loading. import statements are used at compile-time only. It is also advised to avoid importing the entire package as this will increase the compilation time.
// bad practice
// affect compile time eventhough won't affect perfomance on runtime
import java.util.*Auto-Imported Packages
For every source file, we have auto imported packages like java.lang, an unnamed package, and the current package. For example, you might have noticed about String and Integer classes.
Do we actually import String or Integer classes? What do you think?.
We don’t import these classes as they are auto-imported from the java.lang package. It seems interesting right?.
Why do I need Java Imports?
Imports are not actually needed it just makes code more readable and easy to write. see the code example below:
// with importsimport java.util.Map;
import java.util.Hashmap; Map person= new Hashmap();
// without importsjava.util.Map person= new java.util.Hashmap();
Easy way to organize imports
You can configure your eclipse to remove unused imports, unused member variables and provide better coding indentation styling. you can use Ctrl+Shift+O to organize imports or configure eclipse to organize it on saving file
Go to windows > preferences > Java > Editor > save actions


