Java on Linux
Contents
Basic HOWTO
Compiling Java Programs
We'll assume you've written a program in Java and you're ready to compile it. The name you've given the saved file is myprogram.java. The following will compile your program:
javac myprogram.java
The output will be myprogram.class
Executing Java Programs
If you want to execute the program you just compiled, type:
java myprogram
Notice that when you told it to run the program you left the .class off of the filename.
Creating JAR Files
A JAR (Java ARchive) file is a collection of Java files that has been combined into a single file (it also compresses it). This makes it easy to store and redestribute. To create a JAR, go into the directory where all your .class files are and type:
jar cf myjarfile.jar *.class
This is saying to take all my .class files and insert them into a new JAR:
jar cf myjarfile.jar file1.class file2.class file3.class
This is saying to take those three class files and insert them into a new JAR.
Configuring your CLASSPATH
The CLASSPATH is an environmental variable that tells the Java compiler where to look for class files to import or where to find class files to interpret. If you do medium to large Java programming projects you'll probably want to edit this variable. You can set this just like you do your PATH variable. Here is what my CLASSPATH variable is set to:
export CLASSPATH="/opt/jakarta/tomcat/common/lib/servlet.jar:/opt/sun-j2ee-1.3.1/lib/j2ee.jar:/home/emcnabb/postgresql.jar:."
For more information on how to set these variables permanently in your shell, read up on the bash document.
If you want to include class files without actually changing the environmental variables you can do the following:
java --classpath .:class1:class2 myprogram
See the java man page for more details.
Advanced Java Tips
Using Java with Makefiles
If you've used Makefiles in C/C++, you might be wishing you could do the same thing with Java. The Makefile HOWTO explains how to do this.
Using JDB, the Java Debugger
You'll run into bugs that will be hard to find with just println's; that's when debuggers come in handy. The debugger packaged with Sun's Java is JDB. We won't go into detail here about using it, but there are many HOWTOs that will help out.
Also read the JDB manpage.
Where to get more information
Man Pages
For specific information on the java, javac, jar, and jdb commands use the man (manual) pages. Just type the following on the command line:
man java
or:
man javac
or:
man jar
or:
man jdb