Java Print Classpath

In this post, I will be sharing how to print CLASSPATH in Java. We will also discuss what is CLASSPATH, what is default CLASSPATH in Java, how to print the CLASSPATH of the current project, and how to print the CLASSPATH on OS(Windows and Linux).

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


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\.


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.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry