Read Also: Difference between PATH and CLASSPATH in Java
Java Print CLASSPATH
1. What is CLASSPATH?
According to Oracle docs, the CLASSPATH variable is one way to tell applications (JDK tools also), where to look for user classes.
2. How to Print CLASSPATH in Java
You can easily print CLASSPATH in Java using the System.getProperty() method and passing the argument java.class.path. The java.class.path argument extracts CLASSPATH using System.getProperty() and split its paths using String's split() method as shown below in the example:
import java.io.File;
public class PrintClasspathJava {
public static void main(String args[]) {
String classpath = System.getProperty("java.class.path");
String[] cpValues = classpath.split(File.pathSeparator);
for (String cp : cpValues) {
System.out.println(cp);
}
}
}
Output:
C:\Users\SUBMITTAL\Downloads\code\target\classes
C:\Users\SUBMITTAL\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.5.2\spring-boot-starter-web-2.5.2.jar
C:\Users\SUBMITTAL\.m2\repository\org\springframework\boot\spring-boot-starter\2.5.2\spring-boot-starter-2.5.2.jar
C:\Users\SUBMITTAL\Downloads\code\target\classes
C:\Users\SUBMITTAL\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.5.2\spring-boot-starter-web-2.5.2.jar
C:\Users\SUBMITTAL\.m2\repository\org\springframework\boot\spring-boot-starter\2.5.2\spring-boot-starter-2.5.2.jar
3. What is the default CLASSPATH in Java?
Default CLASSPATH in Java is "." i.e. only the current directory is searched.
4. How to print the CLASSPATH of the current project?
If you want to print the CLASSPATH of the current project then use the new File(".").getAbsolutePath() method as shown below in the example:
import java.io.File;
public class PrintCurrentProjectClasspathJava {
public static void main(String args[]) {
String absPath = new File(".").getAbsolutePath();
System.out.println(absPath);
}
}
Output:
C:\Users\SUBMITTAL\Downloads\code\.
C:\Users\SUBMITTAL\Downloads\code\.
From the above, we can conclude that the above Java program prints the current working directory where the program was started.
5. How to print the CLASSPATH on Windows
According to Oracle docs, the CLASSPATH on Windows can be printed using the below command:
C:> echo %CLASSPATH%6. How to print the CLASSPATH on Linux or Solaris
You can print the CLASSPATH on Linux or Solaris using the below command:
% echo $CLASSPATH
That's all for today. Please mention in the comments if you have any questions related to how to print CLASSPATH in Java.