The classpath is not a physical folder but rather a list of locations (directories and JAR files) that the JVM uses to find classes at runtime.
Clarification: Classpath vs. Maven Repository
Concept | What it is? |
---|---|
Classpath | A runtime list of directories and JARs where Java looks for .class files when executing a program. |
Maven Repository (~/.m2/repository/ ) |
A local folder where Maven downloads and stores dependencies. It is not the classpath itself, but dependencies from here can be included in the classpath. |
1. What Exactly is the Classpath?
- The classpath is a set of directories and JAR files.
- When you run a Java application, the JVM loads classes only from the classpath.
- It includes:
- Your compiled
.class
files (fromtarget/classes
). - JAR files from dependencies.
- Your compiled
Example:
If your project has:
- Your compiled files in
target/classes/
- Dependencies in
~/.m2/repository/
Then your classpath might look like:
target/classes:~/.m2/repository/org/springframework/boot/spring-boot-starter-web/3.0.0/spring-boot-starter-web-3.0.0.jar
2. How is the Classpath Defined?
(a) When Running a Java Program Manually
You can explicitly set the classpath when running a Java program:
java -cp target/classes:~/.m2/repository/.../spring-boot-starter-web-3.0.0.jar com.example.MyApplication
Here:
-
-cp
(orCLASSPATH
variable) defines the classpath. -
target/classes
contains your compiled.class
files. - The
spring-boot-starter-web.jar
is needed for Spring Boot.
(b) When Running a Maven Project
Maven automatically sets the classpath when you run:
mvn spring-boot:run
Maven:
-
Compiles your Java files and puts them in
target/classes/
. -
Fetches dependencies from
~/.m2/repository/
. - Starts the application with a fully configured classpath.
(c) When Running from IntelliJ
- IntelliJ automatically sets up the classpath.
- If you go to Run > Edit Configurations, you’ll see:
Classpath: target/classes + Maven Dependencies
3. Viewing the Current Classpath
Method 1: Print Classpath in Java
System.out.println(System.getProperty("java.class.path"));
It prints:
/home/user/project/target/classes:/home/user/.m2/repository/org/springframework/boot/spring-boot-starter-web/3.0.0/spring-boot-starter-web-3.0.0.jar
Method 2: Check Classpath in IntelliJ
- Go to Run > Edit Configurations.
- Look under
Java Options
→ You’ll see all JARs included in the classpath.
Method 3: Use Maven
mvn dependency:tree
Shows all dependencies included in the classpath.
4. Key Takeaways
✅ Classpath is NOT a folder but a runtime list of locations (directories + JARs).
✅ Maven downloads dependencies to ~/.m2/repository/
, but this is NOT automatically the classpath.
✅ When running a Spring Boot app, JVM loads .class
files and dependencies from the classpath.
✅ You can manually define the classpath using java -cp
or check it in IntelliJ.
Top comments (0)