The problem

The HelloWorld code is as follows

package demo;

public class HelloWorld {
    public static void main(String[] args) {
            System.out.println("hello , linux world!");
    }
}
Copy the code

Very simple programs compile first

javac HelloWorld.java
Copy the code

Look at the current directory, also generated helloWorld.class file

Execute using the Java command:

java HelloWorld
Copy the code

Error:

Error: Could not find or load main class HelloWorld
Copy the code

There is some argument that Javac should specify fully qualified class names that contain package names, so let’s decompile the.class file

javap HelloWorld.class
Copy the code

The results are as follows:Discover that there is indeed a fully qualified class name, demo.helloWorld

Continue to try to

java demo.HelloWorld
Copy the code

The same error was reportedAdd classPath as the current classPath folder:

java -classpath . demo.HelloWorld
Copy the code

But it still doesn’t work

Modify the Java file, delete the first line of the package

package demo;
Copy the code

After adding the package name, why can’t we execute it in the same directory as the package name demo

java -classpath .. / demo.HelloWorldCopy the code

This time it worked:You can also successfully switch the directory to the upper layer

conclusion

To execute a class file with a package name using a Java command, the following requirements must be met:

  1. The execution directory is the directory where the outermost layer of the package name resides. For example, the demo folder resides.
  2. The class name needs to include the entire package name, such as demo.helloWorld in this example