Sometimes we need to directly use the Java command provided by the JDK to execute the class file to get the software running, especially many beginners, but often find the following prompt:With an IDE, there is no problem.


why

The reason is simple. We missed two details.

1. By default, the Java directive looks for the address of the class file in the directory specified in the CLASSPATH environment variable.

2. We ignored the impact of package.

The solution

The first problem is easy to solve:

We add “. “directly to the CLASSPATH environment variable. Can. “.” Search the current directory

The second question is analyzed below:

  • Look at the next two classes

  • Class A

    Class B

  • ** The only difference between class A and class B is that the package name is not defined. ** Our project path is D:\HelloWorld, create a SRC folder in the HelloWorld folder, the source files of class B will be placed in SRC. When compiled in javac, newsManager.class is generated in the SRC folder as follows:

  • Execute as follows:

  • Now let’s change the source code to class A again

Why is it wrong after package is added?

  • The path of the package in class A is org.will.app.main. According to Java rules, we should store the source files in the path defined by package. Class A should be placed in:
  • Then we compile and execute:
  • There’s still a question, why, in fact if you go back to your Java books you’ll see that the full name of a class should be the package name plus the class name. Class A full name: org. Will. App. The main. NewsManager

Ok, try again:

Still not right. Why is that?

Look at the map carefully, we in the main directory to the Java command to execute the org. Will. App. The main. NewsManager, it will think class path is:

D:\HelloWorld\ SRC \org\will\app\main\org\will\app\main\NewsManager, as you can see, the path is repeated.

So, we should do this:Success!

conclusion

The Java execution class file is located in the specified CLASSPATH, not in the current directory. If you want it to query the current directory, add “.; “to your CLASSPATH. Represents the current directory.

Java execution class files are strongly dependent on the path of the Package. It will be executed strictly based on the current user path, according to the package specified path to the file path to search for class files. Please pay attention to it from now on. As for all the stuff about adding packages to CLASSPATH on the Internet, there’s not a lot of data out there that really takes the time to analyze it. A lot of it misses the point and is misleading.