Learn to use the -classpath or -cp option in command prompt to set classpath from command prompt in Windows and Linux OS.
1. Class path
- The class path is the path that the Java runtime environment searches for dependencies e.g. classes and other resource files.
- The default class path is the current directory. Setting the
CLASSPATHvariable or using the
-classpathcommand-line option overrides that default. If we want to include the current directory in the search path, we must include
"."(dot or period character) in the list of paths.
- The classpath value set in command prompt is temporary and is not available if we open a new command prompt.
- If we want to set the class path permanently then we should set the class path as environment variable in Windows. In Linux, set the value in bash profile.
2. Setting classpath from command line
There are two ways :
-cpoption while running the java application or tool.
> java -cp .;c:/jars demo-application.jar
set CLASSPATHcommand initially, and then run java application or tool which will search the classes/resources in mentioned paths.
Classpath entries that are neither directories nor archives (.zip or .jar files) nor
> set CLASSPATH .;c:/jars
3. Using wildcards
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 and add star (
-cp c:/temp/lib //includes all classes in the directory 'c:/temp/lib' -cp c:/temp/lib/* //includes all jars in the directory 'c:/temp/lib' -cp c:/temp/lib;c:/temp/lib/* //includes all classes and jars
In any given classpath, sub-directories are not searched recursively. Each directory must be mentioned explicitly.
4. Clearing classpath
To unset a classpath value previously set, use this command to clear its value using am empty value assigned to the variable.
> set CLASSPATH=
Drop me your question in comments.
Happy Learning !!