• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what will happen if we import a package twice

 
PavanPL KalyanK
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

In a class if i declare



Will the compiler load this package twice ??

Please share your ideas
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65229
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you tried it?
 
PavanPL KalyanK
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 65229
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you notice a change in the size of the generated class file?
 
PavanPL KalyanK
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic