2.6. Further Important Notes¶
2.6.1. Setting the Class Path¶
Both javac
and java
allow you to specify the classpath using the
-cp
or -classpath
command-line option. The usual syntax is as
follows:
-cp some/path
If more than one default package is needed, then a colon :
can be
used to separate each path in a list of multiple paths:
-cp path1:path2
Each path can be a path to a directory or a .jar
file (usually used
for third-party libraries).
VERY IMPORTANT NOTE: The classpath should always point to a default
package for compiled code. If you are compiling a .java
file that
depends on an already compiled class, then you will need to specify the
classpath to the corresponding default package for that dependency when
invoking javac
.
2.6.2. Import Statements¶
In Java, you do not have to import classes that are in the same package.
However, it’s interesting to note that import
statements are never
required in Java. We just use them for convenience. Assuming the
corresponding default package for the class’s package is on the
classpath when compiling and/or running, you can always refer to a class
by its fully qualified name. Consider two uses of java.util.Random
below:
// Assuming the class was imported
Random rng = new Random();
// Assuming the class was NOT imported
java.util.Random rng = new java.util.Random();
As you can imagine, the latter (without an import statement) might get
annoying and repetitive. Therefore, we usually prefer to use an
import
statement for the convenience it provides. Why would anyone
prefer to use the fully qualified name instead of the simple name for a
class? It enables you to use two classes from different packages with
the same simple name at the same time!
2.6.3. The java.lang
Package¶
Java automatically performs a wildcard import of the java.lang
package in every Java file, without requiring the programmer to explicitly write it.
That is why you can use classes such as java.lang.String
and java.lang.System
by using their simple names without importing!