Monday, April 13, 2009

Comments in java

We all use comments to describe the Java code. There are three types if comments in Java as demonstrated in this Java tutorial by SUN:

// text

where the compiler ignores everything from // to the end of the line

/* text */

where the compiler ignores everything from /* to */ and

/** documentation */

which is ignored by the compiler the same way as the previous comment type. This one is a special comment as this indicates a documentation comment. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.

I am not going to tell you how to use them. There are many articles and documentation written about that. We all know how to use them and most of us use them on a daily basis. Over time we can develop a stereotype. Mine looks like this:

/** first name */
private String firstName;

/** last name */
private String lastName;

* Constructs and returns the full name
* @return full name
public String getFullName() {
if (firstName == null) {
if (lastName == null) {
// user does not have a name specified
return "[no name]";
else {
return lastName;
else {
if (lastName == null) {
return firstName;
else {
// construct full name from first and last name
return firstName + " " + lastName;

As you can see, I use doc comments to describe the meaning and function of my class members. I also like to use line comments, rather than block comments. Even if my comment spans multiple lines I prefer to use // comments. It's due to my IDE settings. When I press Ctrl+/ it un-/comments the selected lines. It's very neat feature and I use it a lot.

Recently, I was doing some code modifications and I wanted to re-visit some code later. I decide to break the code by putting a comment in the middle if it, so it would not compile and I would be forced to come back to it.

I did somethig like this:

myObject.getAnother()/* change to ID */.getName();

To my surprise the code did not break. Even when I changed it to

myObject.getAnother()./* change to ID */getName();

Obviously, when I did this

myObject.getAnother().ge/* change to ID */tName();

the code broke. At the end I made it to break in a nice way, anyway

myObject.getAnother()./* change to ID */.getName();

No comments: