|Navigate Language Fundamentals topic: )|
A comment allows to insert text that will not be compiled nor interpreted. It can appear anywhere in the source code where whitespaces are allowed.
It is useful for explaining what the source code does by:
- explaining the adopted technical choice: why this given algorithm and not another, why calling this given method...
- explaining what should be done in the next steps (the TODO list): improvement, issue to fix...
- giving the required explanation to understand the code and be able to update it yourself later or by other developers.
It can also be used to make the compiler ignore a portion of code: temporary code for debugging, code under development...
The comments in Java use the same syntax as in C++.
An end-of-line comment starts with two slashes and ends with the end of the line. This syntax can be used on a single line too.
|Code section 3.105: Slash-slash comment.
A comment on several lines is framed with '/' + '*' and '*' + '/'.
|Code section 3.106: Slash-star comment in multiple lines.
By convention, subsequent lines of slash-star comments begin with a star aligned under the star in the open comment sequence, but this is not required. Never nest a slash-star comment in another slash-star comment. If you accidentally nest such comments, you will probably get a syntax error from the compiler soon after the first star-slash sequence.
|Code section 3.107: Nested slash-star comment.
If you need to have the sequence */ inside a comment you can use html numeric entities:
Slash-star comments may also be placed between any Java tokens, though not recommended:
|Code section 3.108: Inline slash-star comment.
However, comments are not parsed as comments when they occur in string literals.
|Code section 3.109: String literal.
It results in a 33 character string.
Comments and unicode
Be aware that Java still interprets Unicode sequences within comments. For example, the Unicode sequence
\u002a\u002f (whose codepoints correspond to */) is processed early in the Java compiler's lexical scanning of the source file, even before comments are processed, so this is a valid star-slash comment in Java:
|Code section 3.110: Unicode sequence interruption.
and is lexically equivalent to
|Code section 3.111: Unicode sequence interruption effect.
'*' character is Unicode
002A and the
'/' character is Unicode
Similar caveats apply to newline characters in slash-slash comments.
|Code section 3.112: New line.
That is because
\u000a is Unicode for a new line, making the compiler think that you have added a new line when you haven't.
Javadoc comments are a special case of slash-star comments.
|Code section 3.113: Javadoc comment.