Differences between java -cp and java -jar?

Differences between java -cp and java -jar?

I prefer the first version to start a java application just because it has less pitfalls (welcome to classpath hell). The second one requires an executable jar file and the classpath for that application has to be defined inside the jars manifest (all other classpath declaration will be silently ignored…). So with the second version youd have to look into the jar, read the manifest and try to find out if the classpath entries are valid from where the jar is stored… Thats avoidable.

I dont expect any performance advantages or disadvantages for either version. Its just telling the jvm which class to use for the main thread and where it can find the libraries.

With the -cp argument you provide the classpath i.e. path(s) to additional classes or libraries that your program may require when being compiled or run. With -jar you specify the executable JAR file that you want to run.

You cant specify them both. If you try to run java -cp folder/myexternallibrary.jar -jar myprogram.jar then it wont really work. The classpath for that JAR should be specified in its Manifest, not as a -cp argument.

You can find more about this here and here.

PS: -cp and -classpath are synonyms.

Differences between java -cp and java -jar?

When using java -cp you are required to provide fully qualified main class name, e.g.

java -cp com.mycompany.MyMain

When using java -jar myjar.jar your jar file must provide the information about main class via manifest.mf contained into the jar file in folder META-INF:

Main-Class: com.mycompany.MyMain

Leave a Reply

Your email address will not be published.