Executable Comments in Java

Java Programming Java8Object Oriented Programming

As we all know, that java compiler ignores the comments written in the java code file. But using a trick we can execute the code present in a comment section. Consider the following program −

Example

public class Tester {
   public static void main(String[] args) {

      // The comment below is magic..
      // \u000d System.out.println("Hello World");
   }
}

This will produce the following result −

Output

Hello World

The reason behind this behaviour is the use of \u000d character in comment which is a new line character. As Java compiler parses the new line character, the put the println command to next line resulting in the following program.

public class Tester {
   public static void main(String[] args) {

      // The comment below is magic..
      //
      System.out.println("Hello World");
   }
}

Reasoning behind this unicode parsing before source code processing is as follows −

  • To keep java source code to be written using any unicode character.

  • To make java code processing easier by ASCII based editors.

  • Helps in writing documentation in unicode supporting languages.

raja
Published on 13-Aug-2018 13:33:44
Advertisements