Compiling Java Classes

3 Compiling Java Classes

Java source code comes in a files with a names ending in .java. For example, your first Java program in a lab might be called something like The Java compiler is called javac, and to compile this file, you would type javac at the command line. If this went well, you would get your command line back with no messages. The compiler creates a file called, in this case, lab1a.class that contains the Java byte code. All the interpreter needs to run your program is the .class file - you could throw away the .java file at this point if you never wanted to make any changes to your program.

Things can go wrong if there are mistakes in your .java file. Here is a session with an error:

(maxwell@gamba.107) javac ';' expected.
        return Math.cos(x)
1 error
The compiler will list errors it found in the file in the order in which it finds them. The format is filename:line-number: error-type, followed by an arrow pointing to the place in the line where the error occurred. So, in the above error, there is a semi-colon missing on line 8 in the file (If you don't know Java grammer yet, don't worry, you will learn about it later. You just need to know here that most lines in Java end with a semi-colon.) The compiler shows that it was expecting something at the end of the line. As you start out, you might see other error messages - use the line number to find the spot in the file and try to guess what might be wrong. Try undoing a recent change and see if that fixes the problem. Also, an error early in the file will often create a slough of errors later in the file, so start with the first errors first, and try recompiling after you have fixed the first few.

One final note: a file called must contain a Java class called myclass in it; otherwise the compiler will fail. So don't rename .java files or you won't be able to compile them.
Next 4 Running Java Programs

David Maxwell, who is still writing this, would like to hear your comments and suggestions.