Last Updated on
The Java comments are lines or portions of code ignored by the compiler and interpreter. Their main purpose is to provide various notes and hints helping to understand the code.
Comments are the most basic form of documentation. In perfect world the code is self-documenting. It means that by reading the code you understand what's happening under the hood. Trying to write such code is a very good practice, but in some cases this is nigh impossible.
For example, a solution might look weird at first sight, but the author did it this way to prevent some obscure bug. This is how it looks in the real world. In that case it would be helpful to include a commentary, so that the future readers will not only understand what the code does, but also why it was done this way, preventing them from falling into the same trap again.
In this article I'm not going to discuss when to use the comments, though. It's a rather broad topic that deserves a separate article. Instead, I'm going show how to use them.
Single and multi-line comments
Single line comments are denoted with double slash, and can be placed in the beginning of a line, or at the end of it. As their name implies, they span a single line.
System.out.println("Hey"); // Prints hey System.out.println("Hello"); // Prints hello
Multi-line comments span several lines, and are started with a slash and asterisk symbol, and ended with an asterisk followed by a slash.
System.out.println("Hey"); /* This line prints hey */ System.out.println("Hello"); /* This line prints hello */
It's a matter of taste whether one uses several single-line comments, or a single multi-line comment. The single-line comments are sometimes preferred because IDEs can comment and uncomment large portions of text with a key shortcut, and they offer more consistent indentation.
// This comment // was written // in multiple lines /* This comment was written in multiple lines */