What Are Java comments?
Java comments are either explanations of the source code or descriptions of classes, interfaces, methods, and fields. This article deals with the former type which are known as implementation comments. They are usually a couple of lines written above or beside Java code to clarify what it does.
Why Use Java Comments?
It's good practice to get into the habit of putting Java comments into your source code to enhance its readability for yourself and other programmers. It isn't always instantly clear what actions a piece of Java code is performing. A few explanatory lines can drastically reduce the amount of time it takes to understand the code.
Do They Affect How The Program Runs?
Implementation comments in Java code are only there for humans to read. Java compilers don't care about them and when compiling the program they just skip over them. The size and efficiency of your compiled program will not be affected by the amount of comments in your source code.
How to Place Implementation Comments in Your Code
Implementation comments come in two different formats:
- Line Comments: When you want to make a one line comment type "//" and follow the two forward slashes with your comment. For example:
// this is a single line comment int guessNumber = (int) (Math.random() * 10);
When the compiler comes across the two forward slashes it knows that everything to the right of them is to be considered as a comment. This is very useful when debugging a piece of code. By adding two forward slashes to the beginning of a line you can hide it from the compiler:
// this is a single line comment // int guessNumber = (int) (Math.random() * 10);
You can also use the two forward slashes to make an end of line comment:
// this is a single line comment int guessNumber = (int) (Math.random() * 10); // this is an end of line comment
- Block Comments: To start a block comment type "/*". Everything between the forward slash and asterisk, even if it's on a different line, will be treated as comment until the characters "*/" end the comment. For example:
/* this is a block comment */ /* so is this */
Tips for Using Comments
- Don't over comment. Every line of your program does not need to be explained. If your program flows logically and nothing unexpected is happening don't feel the need to add a comment.
- Indent your comments. If the line of code you are commenting is indented then make sure your comment matches the indentation.
- Keep comments relevant. Some programmers are excellent at modifying code but for some reason forget to update the comments. If a comment no longer applies then either modify or remove it.
- Don't nest block comments. The following will result in a compiler error:
/* this is /* This block comment finishes the first comment */ a block comment */