Daniel Scocco
Daniel Scocco

Reputation: 7266

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 (e.g., $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 (i.e. Main) in the end?

Upvotes: 0

Views: 963

Answers (1)

len
len

Reputation: 335

  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.

Upvotes: 1

Related Questions