Skip to content

How to set the classpath correctly in java

I need to compile and run simple code using the gson library, but I can’t use Maven, Gradle or the IDE. The directory contains Main.java and gson-2.9.0.jar

javac -cp gson-2.9.0.jar Main.java works correctly and creates Main.class

But when I run java -cp ./*: Main, I get

Error: Could not find or load main class Main.

Caused by: java.lang.ClassNotFoundException: Main

I also tried the following commands:

java -cp gson-2.9.0.jar Main

java -cp gson-2.9.0.jar: Main

java -cp ./gson-2.9.0.jar:./* Main

But all these commands give the same result. I’ve never had to run code from the command line without Maven or IDEA before, so I think it’s the classpath specification that’s the problem. What am i doing wrong here?

Answer

If your main class is in a package (has a package ... declaration), you need to include the package name in the java call, e.g. java -cp ... mypackage.Main.

Additionally, the java documentation says about -cp / --class-path:

As a special convenience, a class path element that contains a base name of an asterisk (*) is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR.

Therefore, using * for .class files does not work; instead you have to specify the directory name. Based on your question it looks like you are using Linux, and that the .class file and the JAR are in the same directory, so the following should work in your case:

java -cp gson-2.9.0.jar:. Main

(note the . after the :, indicating to include the current directory for the classpath)