This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Doubt regarding importing packages Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt regarding importing packages" Watch "Doubt regarding importing packages" New topic
Author

Doubt regarding importing packages

Rohan Deshmkh
Ranch Hand

Joined: Aug 31, 2012
Posts: 127
Is there any advantage of importing particular class from a package over importing the entire package?
Suppose i need to import class Am from package Alphabets, then does
import Alphabets.Am;
have any advantage over
import Alphabets.*;

Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60774
    
  65

There is no difference at run time. Use whichever approach you prefer (or is dictated by the conventions of your workplace).


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Rohan Deshmkh
Ranch Hand

Joined: Aug 31, 2012
Posts: 127
Suppose Alphabets package has more than 100 classes.
Then does using

import Alphabets.Am;
over
import Alphabets.*;

increase performance ,won't importing all the classes from packages take more time than importing a single class?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Rohan Deshmkh wrote:Suppose Alphabets package has more than 100 classes.
...
,won't importing all the classes from packages take more time than importing a single class?


As Bear already stated: There is no difference at run time.

You could import every single class in the core API, or you could import nothing at all, and either way, your .class file will be exactly the same.

Imports are only compile-time syntactic sugar. They have zero effect on the generated .class file, and therefore zero effect at runtime.
Rohan Deshmkh
Ranch Hand

Joined: Aug 31, 2012
Posts: 127
@Jeff : Thanks, i understood.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37953
    
  22
A single‑class import, however, makes it obvious how many classes you are using from that package. It also reduces the risk of collisions like thisIf you look in those two packages, you find each contains a Timer class ←which is what the compiler said!
Rahul mir
Ranch Hand

Joined: Oct 31, 2012
Posts: 38

There is no difference at run time. But in general practice use single‑class import , it is easy for code readability.
 
 
subject: Doubt regarding importing packages
 
Similar Threads
Packages And Import Statement
import package.* Vs package.requiredClass1 , package.requiredClass2 ...
import statements in java
Reflection
Is importing only the necessary files from package advantageos???