简体   繁体   中英

Basic questions about Java CLASSPATH

Suppose I just created a package "example" and have two classes inside it, "Main" and "Helper".

With the simplest possible compilation (eg, $javac Main.java Helper.java) I am already able to run it fine as long as I am in the directory containing the example package, by typing this in the command line:

$java example.Main

Questions:

  1. Why would I want to set a CLASSPATH given I can already run the program? I am guessing to be able to type "$java example.Main" from any directory on my machine, but I am not sure.

  2. What happens when I type "java -cp /path/to/your/java/class/file Main" on the command line? Right now I picture there's file containing all the different classpaths, and that command will just add another one to it. Is it the case?

  3. Is there a difference between using "CLASSPATH=/path/to/your/java/class/file" and "java -cp /path/to/your/java/class/file Main" on the command line? How come the second one has the name of the class (ie Main) in the end?

  1. Yea, pretty much. That of course assumes you have the path to java in your PATH variable
  2. -cp or -classpath adds it's option (a string) in front of whatever is in your CLASSPATH
  3. Yes, there is a difference. Using CLASSPATH is often more convenient as you tend to set your CLASSPATH once. From then on, java Main is enough to execute the main class. With java -cp /path/to/your/java/class/file Main you have to type the -cp /path/to/your/java/class/file every time.

That being said, both CLASSPATH and -cp or -classpath options usually contain entries pointing to directories containing java libraries used by your program, not the directory of your program itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM