Classpath in Java
Classpath in Java
Classpath is a parameter used by the Java compiler (javac) and Java Virtual Machine (JVM) to
locate classes and packages used in a program.
What Classpath Can Include:
- Directories containing .class files
- JAR files
- ZIP files
Setting Classpath:
1. Using Command Line:
java -cp .;lib/myLibrary.jar MyClass
- '.' means current directory
- ';' for Windows, ':' for Linux/Mac
2. Using Environment Variable:
export CLASSPATH=.:/path/to/classes:/path/to/jar/library.jar
3. Using IDE:
Classpath is configurable in most IDEs via project settings.
Why Is Classpath Important?
- Without correct classpath, you may get:
Error: Could not find or load main class MyClass
Example:
If you have:
- MyApp.java in C:\JavaProjects
- utils.jar in C:\libs
You compile and run with:
javac -cp C:\libs\utils.jar MyApp.java
java -cp .;C:\libs\utils.jar MyApp
Default Classpath:
- If not set, default is the current directory ('.')