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:
-
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.
-
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?
-
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?
javain yourPATHvariableCLASSPATHCLASSPATHis often more convenient as you tend to set yourCLASSPATHonce. From then on,java Mainis enough to execute the main class. Withjava -cp /path/to/your/java/class/file Mainyou have to type the-cp /path/to/your/java/class/fileevery time.That being said, both
CLASSPATHand-cpor-classpathoptions usually contain entries pointing to directories containing java libraries used by your program, not the directory of your program itself.