Java Comments

Single-line and multi-line comments in Java

Commenting is a basic feature of almost all mid-level and high-level programming languages. If you have experiences with any other languages then you probably know what comments are.

Comments are used to keep notes about codes in plain English language. It is very helpful for understanding complex code at a later time or code read by other programmers. In java, comments are used to explain complex java code.

In fact, comments help in several ways in programming;

  • Comments are used to explain complex Java code. Which is very useful to understand the code in the future reading time.
  • Comments help to extend the developer and programmer productivity. Because comments help other programmers to understand a complex function written by another programmer.
  • It also helps to reuse the code.
  • Java Comments also can be used to prevent the execution of Java code for trying alternatives.

Java Comments

In Java, comments can be written in two ways;

  • Single line comment: Strats with two forward-slash ( // ). Single line comments are permitted to write in one single line.
  • Multi-line comments: Start with ( /* ) and end with ( */ ). Comments can be written in multiple lines.

TIPS: Normally use single-line comments for shorter comments and use multi-line comments for longer comments

Example

// Hello World print statement
System.out.println("Hello World");

The first line after double forward slash is a single line comment, it will not be executed. We have just discussed the below line. Let’s see a multi-line comment example:

/* The below line express the print statement
    and it is a multi-line comment you see */
System.out.println("Hello World");

Comment: Testing alternative codes

Comments also can be used to test another block or line of code by commenting on a block or line of code instead of removing the actual code. It is very useful that programmers often use it.

//System.out.println("Hello World");
System.out.println("Another Hello World");

You can see in the above code, we have commented on our actual “Hello World” statement to test “Another Hello World”. If you want to back to the actual code again then switch the comment between the test and actual code.

You can also use the multi-line comment to test a full block code in the same way.

Posted in