Distributable Java programs: jar files

A runnable Java program is typically defined by a collection of .class files. You "run" the program by executing the JVM with the name of the class whose main() method is supposed to kick off the program, and as the JVM encounters references to classes it doesn't know about, it looks around for the .class files for those classes, loads them, and continues. It would be quite painful to distribute even relatively small Java programs if it had to be done in this form. The instructions would look like "Download and save the following 27 .class file ...". To get around this, Java has a file format called .jar files, that package many .class files into a single file. If you have a .jar file called Foo.jar, you can run the program it contains with the command:
java -jar Foo.jar
For this example, imagine that we have a solution to Lab12 consisting of files
Decaying.java  DrawArea.java  Free.java  L12.java
Orbit.java  Planet.java  Straight.java	
We would compile this program like:
$ javac *.java
... and run it like:
java L12
... and, as a result, get a beautiful animation of a solar system!
The one thing that's not clear, however, is what class has the main() method that should start things off. After all, many .class files could contain main() methods. The way this is handled is that a file called Manifest.txt is bundled together with all the .class files in the jar file. And Manifest.txt has a line that states which class has the main() method that should be called to kick off the program. Suppose we have the solution to lab 12 shown in the note on the right. The "main" is in L12.java. When we compile this we get lots of .class files, so we would like to distribute this as a jar. We create a jar file by first creating the file Manifest.txt:

Manifest.txt
Main-Class: L12

... and then giving the following command:
jar cfm SolarSystem.jar Manifest.txt *.class
This creates the file SolarSystem.jar that we can send off to other people, who can run it (on any platform with a JVM) with the command:
java -jar SolarSystem.jar
Since the "compiled" code is byte-code compiled for the JVM, rather than true machine-code, it can be run anywhere ... provided the host platform supports the version of Java you compiled to.

For your viewing pleasure, I've included SolarSystemA.jar and SolarSystemC.jar for you to run. Note: beware of running .jar files when you're not absolutely sure that a) the person who wrote it is on the up and up, and b) that you're really gotten the file you think you have!