Could someone give a little background on import statements? When importing a class or classes from a package is there a difference in specifying the class name or just importing with an asterisk (*)? Are these classes allocated in memory? Does it really matter what we use?
Hi Aaron, The answer can be tricky, but in most cases it doesn't matter. Import statements are really just telling the compiler where to search for classes at. Most programmers will just use an asterisk if they are going to use more than 3/4 classes in some package. The compile will only load the classes that are required so no memory space is wasted. The tricky part comes about when we have identically named classes in 2 different packages. The class Date is defined in 2 different packages. Lets look at an example of some usages and problems.
The above code will result in compilation errors because the compiler can't figure out which Date class to use. If we make one small change the program can compile and execute without errors.
Now the compiler will go ahead and use the sql version of Date because we have specified it exactly on the import line. The positioning of exact specifications doesn't matter but they do take precedence over using an asterisk. That means that swapping the import lines above will not cause any compiler error to appear. Regards, Manfred.
Joined: Aug 16, 2001
You said....The compile will only load the classes that are required so no memory space is wasted....so an import with an asterisk would be more of a memory requirement than just a class import? How big of a hit are we talking?
Joined: Jan 09, 2001
Hi Aaron, Read the sentence again ... we are not taking any hit.
The JVM will only load classes that are needed.
The above statement is valid no matter how you type the import statement (asterisk or specific). In my previous example, it we didn't use any Date class the JVM will not load any Date class! Manfred.