aspose file tools*
The moose likes Beginning Java and the fly likes what will happen if we import a package twice Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "what will happen if we import a package twice" Watch "what will happen if we import a package twice" New topic
Author

what will happen if we import a package twice

PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212

In a class if i declare



Will the compiler load this package twice ??

Please share your ideas
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61221
    
  66

What happened when you tried it?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212
The program compiled and ran well .

But how can i know whether the package has been loaded once/twice ??

Please tell .
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61221
    
  66

Did you notice a change in the size of the generated class file?
PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212
I could not rely on the size it is of 1kb

Even when i loaded
import java.util.*;
import java.beans.*;

the size is same 1kb


PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212
I found the answer

Can I import same package/class twice? Will the JVM load the package twice at runtime?
A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

"import" is an instruction to the compiler so it knows which class you're talking about when you say "new ArrayList()" or "Collections.sort()". In no sense does the compiler load, incorporate, read, input, store or otherwise manipulate any classes because of an import statement. If you added a million import statements for a million different classes to a source file, the class compiled from that source file would be identical and wouldn't grow by a single byte.


[Jess in Action][AskingGoodQuestions]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38865
    
  23
Try the javap tool.

javap -c MyClass

See how many differences you can find when you import one package or several packages. As long as you don't have a collision, like this class and this one imported together, you should get that to work all right.
If the .class file is too large for javap, try a hexadecimal editor and inspect the bytecode.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what will happen if we import a package twice