Java: running a class from a package
The tutor discusses a trick of command-line Java.
Programmers are trained to organize related files in coordinated folders. Older people – or Linux people – might prefer “directory” to “folder.”
However you see it, a way to organize related files in Java is to identify them as belonging to the same package. All the members of that package are stored in the same directory, which is named the same as the package.
Each file in a package must declare, on its first line,
package nameofpackage;
Let’s imagine, for instance, a package called P1. Then each file in it contains the first line
package P1;
Every file in that package is stored in the folder P1
A file in a package can be compiled from within the package directory, but running it might be easier to do from the directory above it. Let’s image that, in the package P1, the file containing the main() method is called P1Driver. Furthermore, let’s imagine the full path to P1Driver is
/javaprojects/P1/P1Driver.java (in Linux)
or
c:/javaprojects/P1/P1Driver.java (Windows)
In either case, one way to run P1Driver, once compiled, might be to back out to the directory above it:
/javaprojects or c:/javaprojects
then, from there, try the command
java P1.P1Driver (Linux)
or, in Windows:
java -cp . P1.P1Driver
There are many fine points to discuss concerning Java. HTH:)
Source:
Schildt, Herbert. Java: the Complete Reference. New York: McGraw Hill, 2011.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.