Online Test Banks
Score higher
See Online Test Banks
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use Comments in Java

A comment in Java is a bit of text that provides explanations of your code. The compiler ignores comments, so you can place any text you want in a comment. Using plenty of comments in your programs is a good idea to explain what your program does and how it works.

Java has two basic types of comments: end-of-line comments, and traditional comments.

An end-of-line comment begins with the sequence // (a pair of consecutive slashes) and ends at the end of the line. You can place an end-of-line comment at the end of any line. Everything you type after the // is ignored by the compiler. For example:

total = total * discountPercent; // calculate the discounted total

If you want, you can also place end-of-line comments on separate lines, like this:

// calculate the discounted total
total = total * discountPercent;

You can also place end-of-line comments in the middle of statements that span two or more lines. For example:

total = (total * discountPercent)  // apply the discount first
      + salesTax;                  // then add the sales tax

A traditional comment begins with the sequence /*, ends with the sequence */, and can span multiple lines. Here’s an example:

/* HelloApp sample program.
   This program demonstrates the basic structure
   that all Java programs must follow. */

A traditional comment can begin and end anywhere on a line. If you want, you can even sandwich a comment between other Java programming elements, like this:

x = (y + /* a strange place for a comment */ 5) / z;
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.