Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 436
Jomia Avatar asked Mar 20 '11 02:03

Jomia


People also ask

How can we access class in another package?

To import the java package into a class, we need to use the java import keyword which is used to access the package and its classes into the java program. Use import to access built-in and user-defined packages into your java source file to refer to a class in another package by directly using its name.

Which keyword is used for accessing the classes in a package?

Explanation: The import keyword is used to access the classes and interfaces of a particular package to the current file.

Which of the following is the correct way of define a class that will be in the default package?

The only way to access classes in the default package is from another class in the default package. In that case, don't bother to import it, just refer to it directly. This is actually the right answer to the question.


1 Answers

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

like image 50
Piyush Mattoo Avatar answered Oct 14 '22 18:10

Piyush Mattoo