Regarding memory there is no difference, the instruction import
serves only to tell where the classes used are.
But there is an advantage in using it directly importing the class. If there are classes with the same name in two packages a conflict will occur in which class is being referenced.
For example, using the packages javax.swing.text
and org.w3c.dom
, whereas the two have the class Element
:
import javax.swing.*;
import org.w3c.dom.*;
...
Element elemento;
In this case the Element
used is which package?
Already in the following example:
import javax.swing.text.Document;
import org.w3c.dom.Element;
...
Element elemento;
We know so that the Element
used is from the package org.w3c.dom
. So in reality there is an advantage in spelling out the imported classes in the context of facilitating the reading and understanding of the code. Not that it matters *
whether bad or wrong, only facilitates future maintenance.
Import all classes from a package with *
is justified only by the ease of not having to change imports manually for each new class used. To facilitate this aspect and to avoid it being necessary to have knowledge of the exact path to the package that will be used, the main IDEs
developmental Java
have shortcuts to optimize imports, removing those that are not being used and presenting package options for those that are not declared. Some are listed below (In the default setting):
- Netbeans: Ctrl + Shift + I
- Eclipse: Ctrl + Shift + The
- Intellij: Ctrl + Alt + The
Answer references for similar questions on Stack Overflow:
The second option, the correct one is to import the class you will use directly, unless you are going to use all the classes of a very extensive package, then the call with the joker compensates more, but I can’t imagine a scenario where this will occur.
– user28595
Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).
– Sorack