dcsimg
 

Magical comments in Java Explained

Friday Apr 30th 2021 by MS Sridhar
Article Image

When using magic comments in our documentation, we need to be careful about their usage. We explore this in today’s Java programming tip.

In Java, there are a few exceptions on how commented lines are treated. Magical comments fall into this category. When using magic comments in our documentation, we need to be careful about their usage. We explore this in today’s Java programming tip.

Note in the sample code below that even though all three lines in our main method are commented, the line numbers two and three are still executed. When Java finds text \u000d, it interprets it as a new line, and the text following it is processed, accounting for this unexpected behavior.

Here is an example code using the Java programming language showing magical comments in action:

*/

public class ExecutingComments {
    public static void main(String []args)
    {
         // The next line is commented
         // \u000d System.out.println("This line is commented, but still executed");
         // \u000d System.out.println("Sum of (1+2): " + (1+2));
    }
}

/*

The above code snippet showcasing magical comments in Java should result in the following output:

$java ExecutingComments
This line is commented, but still executed
Sum of (1+2): 3
Home
Mobile Site | Full Site