This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

preface

In Linux, when executing Java programs, you need to use java-jar or java-cp to specify the jar to run. The two ways of running mechanism is not the same, today to check the difference between the two ways of running.

Execute a program

Let’s say we have a program, packaged here as test.jar, how to run it to successfully print Hello World.

The code is as follows:

package com.test;
public class Test {
    public static void main(String[] args) {
        System.out.println("Hello World"); }}Copy the code

We commonly have the following two methods to run:

1. java -jar Test.jar
2. java -cp com.test.Test Test.jar
Copy the code

Here’s how -JAR works.

java -jar

The manifest.MF file is in the meta-INF folder.

The content is as follows:

We know that to run a Java program, we must have a main() method as an entry point in order to start the program.

Java-jar, on the other hand, finds the Test Class by main-class and executes Main (), printing Hello World! Your manifest.mf file will display a Cant load main-class error if there is no main-class in it. So you must specify main-class when exporting jar packages or using Maven to package plug-ins.

As shown in figure:

When exporting, the MF file will have the entry class information.

java -cp

For Java-cp there is no need to specify main-class to specify entry. Because at startup, the first argument specifies your entry class, and the second argument is your JAR package. It will find the Test class specified by the first argument based on your jar package and print HelloWorld.

The difference between

Let’s say we need to rely on a package called dep.jar to run our program.

If we use -jar, we need to package dep. jar with test. jar, because -jar can specify only one JAR package.

If -cp is used, we can either put dep.jar in test. jar or run it with the following command:

java -cp com.test.Test Test.jar:Dep.jar
Copy the code

Cp is actually the classpath, which is used in Linux for multiple JAR packages: split, representing all the JAR packages needed to run the program.

This way, you don’t have to package all your dependencies together under test.jar. The advantage of this method is that if you modify the Test class, you can only upload the modified test.jar to the server. You do not need to package all dependencies into test.jar and upload again, saving time.