Java Notes
Comments
Computer programs are read by both computes and humans. You write Java instructions to tell the computer what to do. You must also write comments to explain to humans what the program does. Of course, Java can't understand them because they are written in English, or Spanish, or Thai, or ... .
Java ignores all comments. There is, however, a program called javadoc which reads certain kinds of comments and produces HTML documentation (see below).
Spaces and blank lines
One of the most effective ways to make a program readable is to put spaces in at key points. There are several styles for doing this. Even more important is to put blank lines in your program. These should separate sections of code. There should be a blank line between each "paragraph" of code. By paragraph, I mean a group of statements that belong together logically; there is no Java concept of paragraph.
Java comments
- // comments -- one line
-
After the two
//
characters, Java ignores everything to the end of the line. This is the most common type of comment.//--- local variables --- int nquest; // number of questions. int score; // count of number correct minus number wrong.
- /* ... */ comments -- multiple lines
-
After the
/*
characters, Java will ignore everything until it finds a*/
. This kind of comment can cross many lines, and is commonly used to "comment out" sections of code -- making Java code into a comment while debugging a program. For example,/* Use comments to describe variables or sections of the program. They are very helpful to everyone who reads your programs: your teacher, your boss, but especially yourself! */
- javadoc comments
-
Comments that start with
/**
are used by thejavadoc
program to produce HTML documentation for the program. The Java documentation from Sun Microsystems is produced using javadoc. It is essential to use this kind of comment for large programs.
Best Practices
- Don't write comments to document obvious statements. Assume the reader knows Java.
- Every comment has the potential to create an inconsistency between what the comment says, and what the code does. One cause of "software rot" is that code is changed over time, but comments are not updated. To avoid this, keep comments next to the code that is documented so that they may be more easily synchonized.
Interesting comments
- Write Sweet-Smelling Comments by Mike Clark.
- Otaku, Cedric's weblog
- Cenqua's The Commentator -- Humor warning.