How to Leave Comments in Java Code
Comments are a powerful tool. They can be used to generate entire application programming interface (API) documentations with tools like javadoc, give small hints in tricky parts of code, or just describe what the code is about to do. When you leave comments in Java code, you can also show a reader who doesn't know the language exactly what the code is doing.
Instructions
-
-
1
Leave short, single-line comments to say something quickly before a small group of lines. Small comments outline what's being done in general "chunks." A programmer will often write these comments first and go back to fill in the code afterward, helping him to cement his mental image of how the code will work prior to writing it, as well as identifying any flaws in logic before writing the code.
-
2
Know the format for leaving single-line comments. They are noted by "//".
""// Connect to the server
Socket s = new TCPSocket();
s.connect("example.com", 80);// Request the file
s.write("GET / HTTP/1.0\r\n\r\n");
string response = s.read();// Was the request successful?
int code = get_code(response);
if( code != 200 ) return -1;// Download the file
download_file(s);"" -
-
3
Use multi-line comments when you have more to say than will fit in a single line. Multi-line comments are usually found at the top of methods describing overall function, how it works and what parameters it takes. They're also sometimes seen in localized parts of code the programmer had trouble with or thinks warrant in-depth discussion.
-
4
Note the general format of multi-line comments. By convention, each line begins with an asterisk. The only specific format requirements are that the comment begins with /* and ends with */.
""/* This part was really tough. I had to
* hack this value to fit with the others.
* Maybe I'll come back to this code to
* find a better way to do this, but for
* now this works, but it's not pretty.
*/"" -
5
Know the format of Javadoc comments. They begin with /** and contain meta-tags that look like @this. Javadoc comments are mainly found before methods.
""/**
* Computes the slope of a line.
*
* @Author Jack Smith
* @param p1 First point that describes the line
* @param p2 Second point that describes the line
* @return Slope of the line as a float
*/""
-
1
Tips & Warnings
Develop a balance of comments when writing your code. Too many comments actually makes the code harder to read. When the code is easy to follow, there's no point in writing comments for every line. At the other extreme, code with no comments can be difficult to read if the reader doesn't understand fully what the code is doing.
In Java, you also see javadoc meta-tags in multi-line comments.