If I access a class within a package using fully qualified name, without importing it, whether it saves any memory?
Using fully qualified class name :
java.lang.Math.sqrt(x);
Import package :
import java.lang.Math;
Math.sqrt(x);
which is the better way : import the package or access using fully qualified name?
Thanking you..
No, it doesn't save you memory.
Also note that you don't have to import Math
at all. Everything in java.lang
is imported automatically.
A better example would be something like an ArrayList
import java.util.ArrayList;
....
ArrayList<String> i = new ArrayList<String>();
Note I'm importing the ArrayList
specifically. I could have done
import java.util.*;
But you generally want to avoid large wildcard imports to avoid the problem of collisions between packages.
They're equivalent. The access is the same.
The import is just a convention to save you from having to type the fully-resolved class name each time. You can write all your Java without using import, as long as you're a fast touch typer.
But there's no difference in efficiency or class loading.
Import package is for better readability;
Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName()
.
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
Source: Stackoverflow.com