In Java we can either import single classes as well as the whole set of classes (a package).
As an example
import java.util.*
includes
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Iterator;
import java.util.Map;
Other than the length of the code, are there any specific advantages of using the each approach in any manner? Memory allocation? Performance?
If you want to find static methods in the imported class, you should type class name the press dot(.) to trigger the proposal. Eg: YourImportedClassName. In Java, you do not need to add import statements for classes that exist within the same package (they are actually automatically “imported” by the compiler).
As discussed above the package keyword is used to group certain classes and interface under one package and, the import keyword is used include/use the classes and interface from a package in the current program.
The import statement is optional, and we can use the fully-qualified name of the class to refer to a class or package in the program. This method tells the compiler that the class is defined under a particular package, and we want to use that class or classes in our program.
There is no performance or memory allocation advantage to either -- they both will compile to the same bytecode.
The import
statement is to tell the compiler where to find the classes that the source code is referring to.
However, there is an advantage to importing only by classes. If there is a class with the exact same name in two packages, there is going to be a conflict as to which class is being referred to.
One such example is the java.awt.List
class and the java.util.List
class.
Let's say that we want to use a java.awt.Panel
and a java.util.List
. If the source imports the packages as follows:
import java.awt.*;
import java.util.*;
Then, referring to the List
class is going to be ambigious:
List list; // Which "List" is this from? java.util? java.awt?
However, if one imports explicitly, then the result will be:
import java.awt.Panel;
import java.util.List;
List list; // No ambiguity here -- it refers to java.util.List.
The imports you choose to use only make a compile-time difference when resolving class names.
So the only advantages/disadvantages apply to readability.
Only importing the minimum you require seems better because someone can look at what you actually are using. That said, the IDE probably handles this and it's a moot point.
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