To compile a java program (with .java extension), you need to compile it from the same directory where it is located, or you can also specify where it is. For example, here is my PackageDemo.java, A.java and D.java codes:
I put PackageDemo.java in directory Documents/JavaFiles/sources/packagedemo. In my directories, I separated the source files and the class files. So, all the .java files are in the Documents/JavaFiles/sources folder along with their package names as the subdirectories. All the .class files are in Documents/JavaFiles/classes folder. The way I compile PackageDemo.java is that I specify where I want the compiler to put the .class files by:
By this, the compiler will automatically compile A.java and D.java. It also automatically creates 3 extra folders in my Documents/JavaFiles/classes directory, namely:
- 1 for package packagedemo (from PackageDemo.java) that contains PackageDemo.class. This is because we specify it in our program by the statement of "package packagedemo;"
- 1 for package abc (from A.java) that contains A.class. Again, this is because we specify it in A.java by the statement of "package abc;"
- 1 for package def (from D.java) that contains D.class. Again, this is because we specify it in D.java by the statement of "package def;"
![]() |
Folders created automatically by compiler because of the 'package' statement in each .java code |
How to run the PackageDemo.class? I do it from the parents directory that contains the packages, that is from Documents/JavaFiles/classes directory. This make sense because the JVM, just like the Java compiler in this case, looks for .class files by using a class loader that searches, in order, through:
- the standard Java classes first that are bundled with the JDK.
- If not found, it goes to extension classes provided by the Java's extension mechanism.
- If still not found, the class loader searches the classpath, which by default is the current directory.
Here is the command line for running PackageDemo.class and the result:
You can set up your own classpath if you want. This can be done in 2 ways:
- provide -classpath option when compiling to command line javac
- set you CLASSPATH environment variable