Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: import statement vs fully qualified name?

Tags:

java

import

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.

like image 796
Jonathan Pitre Avatar asked Aug 10 '12 18:08

Jonathan Pitre


People also ask

Can we give fully qualified class name instead of importing the class?

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.

What is fully qualified name in Java?

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.

What is the advantage of using import statements in Java?

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.

Which is a risk of using fully qualified class name when importing?

Explanation: Memory usage is increased. The compiler runs longer. Performance of the code is reduced.


2 Answers

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.

like image 193
sundar Avatar answered Sep 20 '22 20:09

sundar


None, in my opinion. Look at the bytecode - there will be no difference.

 javap -c <your class>
like image 40
Eugene Avatar answered Sep 22 '22 20:09

Eugene