Thursday, 16 August 2012

Javac and Java Command Lines

javac and java commands are the most basic thing in Java Programming. If you are programming using an IDE, such as Netbeans-like me, this might not be a problem. However, if you use command line and compile-run your Java programs from the shell, then you might need to read on.

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:
javac -d command

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:
  1. the standard Java classes first that are bundled with the JDK. 
  2. If not found, it goes to extension classes provided by the Java's extension mechanism. 
  3. 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:

Java command line
Result of the above command line
You can set up your own classpath if you want. This can be done in 2 ways:
  1. provide -classpath option when compiling to command line javac 
  2. set you CLASSPATH environment variable


No comments:

Post a Comment