Topic 5: Comments

A comment is a text that the compiler ignores but that is useful for programmers. Comments are normally used to annotate code for future reference. The compiler treats them as white space. You can use comments in testing to make certain lines of code inactive.

A java comment is written in one of the following ways:

  • The /* (slash, asterisk) characters, followed by any sequence of characters (including newlines), followed by the */ characters.
  • The // (two slashes) characters, followed by any sequence of characters. A new line not immediately preceded by a backslash terminates this form of a comment. Therefore, it is commonly called a "single-line comment."

The comment characters (/*, */, and //) have no special meaning within a character constant, a string literal, or a comment.

Example 1: Single line comment
  • // declaring a variable
    int a;

    // initializing the variable 'a' with the value 2
    a = 2;
Example 2: Multiline line comments
  • /* declaring a variable
    to store salary for employees
    */
    int salary = 2000;