Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The comments can be used to provide information or explanation about the variable, method, class or any statement. It can also be used to hide program code for specific time.

In programming, comments are portion of the program intended for you and your fellow programmers to understand the code. They are completely ignored by Java compilers.

Use Comments the Right Way

Comments shouldn't be the substitute for a way to explain poorly written code in English. Write well structured and readable code, and then use comments.

Some believe that code should be self-documenting and comments should be scarce. However, I have to disagree with it completely (It's my personal opinion). There is nothing wrong with using comments to explain complex algorithms, regex or scenarios where you have chosen one technique over other (for future reference) to solve the problem.

In most cases, use comments to explain 'why' rather than 'how' and you are good to go.

Types of Java Comments

There are 3 types of comments in java.

  • Single Line Comment
  • Multi Line Comment
  • Documentation Comment
1) Java Single Line Comment

The single line comment is used to comment only one line.

//This is single line comment
public class CommentExampleSingeCom { public static void main(String[] args) { int i=31;//Here, i is a variable System.out.println(i); } }

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

/* This is multi line comment */
public class CommentExampleMultiLine { public static void main(String[] args) { /* Let's declare and print variable in java. */ int i=3136; System.out.println(i); } }

3) Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation API, you need to use javadoc tool.

/** This is documentation comment */
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/ public class Calculator { /** The add() method returns addition of given numbers.*/ public static int add(int a, int b){return a+b;} /** The sub() method returns subtraction of given numbers.*/ public static int sub(int a, int b){return a-b;} }