Java Tricks: Commenting Out Code

How do you comment out code? Using /*...*/? Using your IDE to put // before each line? There is a third method:

    if (0 == 1) {
        ... code ...
    }

Pros:

  • Nests
  • You need only change a single character to “flip” the comment: Replace the 0 with 1.
  • You won’t get warnings because of suddenly unused imports or local variables.
  • The Java compiler will remove this block of code in the optimization step, so no runtime penality.

Cons:

  • Can only be used inside of methods.

If you need a fast way to repeatedly comment in/out a piece of code elsewhere, use this syntax:

    //* Fast flip comment starts here
        ... code ...
    /* and ends here */

Inside of a /*...*/ comment, the sequence “/*” has no special meaning. To comment out the block of code, remove the first “/” in “//*”:

    /* Fast flip comment starts here
        ... code ...
    /* and ends here */

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s