Jomia
Jomia

Reputation: 3404

Java : Accessing a class within a package, which is the better way?

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..

Upvotes: 13

Views: 219485

Answers (5)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74760

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.)

Upvotes: 2

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

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().

Upvotes: 0

Piyush Mattoo
Piyush Mattoo

Reputation: 16125

There is no performance difference between importing the package or using the fully qualified class name. The import directive is not converted to Java byte code, consequently there is no effect on runtime performance. The only difference is that it saves you time in case you are using the imported class multiple times. This is a good read here

Upvotes: 13

Brian Roach
Brian Roach

Reputation: 76908

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.

Upvotes: 8

duffymo
duffymo

Reputation: 308763

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.

Upvotes: 4

Related Questions