Hi, I have a question about the "import" keyword in java program: In any java program, when you use the "import" keyword in the begining of the program, exactly what happens? If I want to use the "Vector" class and I add "import java.util.*", is that considered as an overkill? (Since I can get the job done by only import "java.util.Vector".) Will the generated class file run faster if I only import the exact class I need in my program other than import the whole package? I guess in the compiling stage, whether my program import only "java.util.Vector" or the whole package "java.util.*" does not matter. The generated class file should be of the same size under either circumstances, am I right? But in the link stage, where the precompiled Vector class is found in the classpath and run, is there any difference under the above two cases?
Tieyi - Please change your screen name to conform to JavaRanch's naming policy. The import keyword makes your program aware, at compile-time, of the available ways to resolve class definitions. You can avoid imports altogether, if you wish, simply by applying fully-qualified names to all the classes you reference. Wildcards reduce the number of imports you have to write in some cases, but there is some potential for ambiguity, if for example a class uses two different String types. All references are fully qualified in the bytecode to ensure type safety.
Make visible what, without you, might perhaps never have been seen. - Robert Bresson
Joined: Mar 22, 2002
Will the generated class file run faster if I only import the exact class I need in my program other than import the whole package?
No, unlike C or C++ the final "executable" does not increase by including other classes. If you have classes with the same name coming from different packages you must use the fully-qualified name, e.g. java.util.Date, java.sql.Date. -anthony
Joined: Dec 04, 2000
However, I would personally recommend using the fully qualified path name, and not just the package name. This is useful when reviewing code, to better understand what it is and isn't doing, since you can immediately know what type of classes are involved just by looking at the import statements, which are usually organized by package and/or alphabetically. --Mark
Joined: Feb 04, 2002
If you ever stumble across code with wildcard imports you can compile the code in verbose mode and it will list the classes it is loading (and therefore using). Can sometimes help ...