Use Comments to Experiment with Java Code

By Barry Burd

You may hear programmers talk about commenting out certain parts of their Java code. When you’re writing a program and something’s not working correctly, it often helps to try removing some of the code. If nothing else, you find out what happens when that suspicious code is removed.

Of course, you may not like what happens when the code is removed, so you don’t want to delete the code completely. Instead, you turn your ordinary Java statements into comments. For instance, you turn the statement

System.out.println("I love Java!");

into the comment

// System.out.println("I love Java!");

This change keeps the Java compiler from seeing the code while you try to figure out what’s wrong with your program.

Traditional comments aren’t very useful for commenting out code. The big problem is that you can’t put one traditional comment inside of another. For instance, suppose you want to comment out the following statements:

System.out.println("Parents,");
System.out.println("pick your");
/* 
 * Intentionally displays on four separate lines
 */
System.out.println("battles");
System.out.println("carefully!");

If you try to turn this code into one traditional comment, you get the following mess:

/*
  System.out.println("Parents,");
  System.out.println("pick your");
  /* 
   * Intentionally displays on four separate lines
   */
  System.out.println("battles");
  System.out.println("carefully!");
*/

The first */ (after Intentionally displays) ends the traditional comment prematurely. Then the battles and carefully statements aren’t commented out, and the last */ chokes the compiler. You can’t nest traditional comments inside one another. Because of this, you should use end-of-line comments as tools for experimenting with your code.

Most IDEs can comment out sections of your code for you automatically.

Why might you not code comments? Three little words: “Know your audience.” When you write complicated, real-life code, your audience is other programmers, information technology managers, and people who need help deciphering what you’ve done.