Java Reference
In-Depth Information
Note
The compiler automatically imports the
String
class and other types from
the
java.lang
package, which is why it is not necessary to qualify
String
with
java.lang
.
Searching for Packages and Types
Newcomers to Java who first start to work with packages often become frustrated by
“no class definition found” and other errors. This frustration can be partly avoided by
understanding how the JVM searches for packages and types.
Thissectionexplainshowthesearchprocessworks.Tounderstandthisprocess,you
needtorealizethatthecompilerisaspecialJavaapplicationthatrunsunderthecontrol
of the JVM. Furthermore, there are two different forms of search.
Compile-Time Search
Whenthecompilerencountersatypeexpression(suchasamethodcall)insourcecode,
itmustlocatethattype'sdeclarationtoverifythattheexpressionislegal(amethodex-
istsinthetype'sclasswhoseparametertypesmatchthetypesoftheargumentspassed
in the method call, for example).
The compiler first searches the Java platform packages (which contain class library
types).Itthensearchesextensionpackages(forextensiontypes).Ifthe
-sourcepath
command-lineoptionwasspecifiedwhenstartingtheJVM(via
javac
),thecompiler
searches the indicated path's source files.
Note
Javaplatformpackagesarestoredin
rt.jar
andafewotherimportantJAR
files. Extension packages are stored in a special extensions directory named
ext
.
Otherwise,thecompilersearchestheuserclasspath(inleft-to-rightorder)forthefirst
userclassfileorsourcefilecontainingthetype.Ifnouserclasspathispresent,thecur-
rent directory is searched. Ifnopackage matches orthe type still cannot be found,the
compiler reports an error. Otherwise, the compiler records the package information in
the classfile.
Note
Theuserclasspathisspecifiedviathe
-classpath
optionusedtostartthe
JVM or, if not present, the
CLASSPATH
environment variable.