In this tutorial, we will learn ‘How to set Classpath’ in Java . The classpath is a variable of Java language. It is used for accessing a class from one directory to another directory, it means if we want to access a .class file that is available either in another directory or in the other project directory without copying into our project directory or without changing directory by setting classpath with that directory path.
javac -d C:\Test Demo.java
-Here we getting an error because .class file is not available in this folder. .class file is present in C: drive in Test directory.
-We will set classpth by using java tool.
There are 5 ways to set classpath
1. By using java option ‘-cp’
2. By using java option ‘-classpath
3. By using java option ‘–class-path’
java -cp C:\Test DemoClass
java -classpath C:\Test DemoClass
java --class-path C:\Test DemoClass
-The Java tool options ‘-cp’ or ‘-classpath’ or ‘–class-path’ used for setting only for this one command line temporary. In next command line this classpath setting is not available. We will get error ‘ClassNotFoundException’.
4. By using ‘set classpath’ command :We must use ‘set classpath’ command to have classpath for the entire command prompt.
set classpath = C:\Test
-The problem with ‘set classpath’ approach, the classpath setting are available only for this command prompt. By using this command we can set temporary classpath.
5. By using environment variable window: For permanent setting we have to set classpath in environment variable window.
Steps:
- Write click on ‘This PC’
- Click ‘properties’
- Click ‘Advanced System Setting’
- click on ‘Environment variable’
- In ‘System variable’ section click ‘New’ & add “variable name = classpath & Variable value = C:\Test => then click ‘Ok’ “.
- Now close all window, open new command prompt run Demo class again.