Learn to use the -classpath or -cp option to set the Java classpath from the command prompt in Windows and Linux OS.
1. Java Classpath
- The classpath is the list of directory locations that the Java runtime environment searches for the classes and other resource files, during program execution.
- The default classpath is the current working directory.
- Setting the
CLASSPATH
environment variable or using the-classpath
command-line option overrides the default value. - If we want to include the current working directory in the classpath, we must include
"."
(dot or period character) in the list of paths. - The value of classpath set from the command prompt is temporary and is not available if we open a new command prompt.
- If we want to set the classpath permanently then we should set the classpath as environment variable in Windows. In Linux, set the value in bash profile.
Path Separators are Platform Dependent
The separator between two paths in the classpath value is platform-dependent.
In Windows, the path separator is semicolon ( ; ) and the path separator in Linux is colon ( :
).
2. Setting Classpath from Command Line
There are two ways :
- Use
-classpath
or-cp
option to provide the classpath locations while starting the Java application or tool.
java -cp .;c:/jars demo-application.jar
- Use
set CLASSPATH
command initially, and then run Java application or tool in the same command line window. “
It will search the classes/resources in mentioned classpath locations.
Classpath entries that are neither directories nor archives (.zip or .jar files) nor*
are ignored.
set CLASSPATH .;c:/jars
The above examples are specific to Windows. Please use colon as the path separator for Linux.
3. Wildcards in Classpath
Generally, we will include two kinds of resources in classpath i.e. classes and jar files.
- To include classes, give the complete path of the folder where classes are present.
.
(dot) represent the current directory. - To include jar files, give the complete path of the folder where jars are present. Add a star (
*
) wildcard for adding all jar files in that directory.
Please note that the jar files present in the sub-directories are NOT included automatically. Sub-folders must be included explicitely.
java -cp c:/temp/lib applation.jar //includes all classes in the directory 'c:/temp/lib'
java -cp c:/temp/lib/* application.jar //includes all jars in the directory 'c:/temp/lib'
java -cp c:/temp/lib;c:/temp/lib/* application.jar //includes all classes and jars
4. How to Clear Classpath Value
To unset a classpath value previously set, use this command to clear its value using am empty value assigned to the variable.
set CLASSPATH=
Happy Learning !!
Comments