I've tried finding an answer to this both online and in my own set of knowledge, but I cannot seem to find a definitive, clear answer.
Suppose I'm using only one class from another package only once which needs to be imported, say myPack.anotherPackage.ClassName
.
What is the difference, if any, between using an import statement:
import myPack.anotherPackage.ClassName;
versus using a fully qualified name:
myPack.anotherpackage.ClassName classInst = new myPack.anotherpackage.ClassName();
?
Obviously this question only applies if ClassName
is only used once.
3) Using fully qualified name Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
A fully-qualified class name in Java contains the package that the class originated from. An example of this is java. util. ArrayList. The fully-qualified class name can be obtained using the getName() method.
Import statement in Java is helpful to take a class or all classes visible for a program specified under a package, with the help of a single statement. It is pretty beneficial as the programmer do not require to write the entire class definition. Hence, it improves the readability of the program.
Explanation: Memory usage is increased. The compiler runs longer. Performance of the code is reduced.
Import statements make your code more readable, since you are not cluttering the code with the complete package.
In case if there is a conflict of ClassNames
, then only in that case it is advisable to go for fully qualified names.
None, in my opinion. Look at the bytecode - there will be no difference.
javap -c <your class>
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