How to execute Java code within Java comments
We all know Java comments are not visible to compiler and are not executable. But here we will see how a comment can be executed. To execute any comment we need to append a unicode as prefix to that comment and thats it. Now when you will run the code then this comment line will be executed.
[java]
public class CommentTest {
public static void main(String[] args)
{
// Following line will be executed and will produce output.
// \u000d System.out.println("This is the output generated from commented line");
}
}
[/java]
Output: This is the output generated from commented line
Why this is happening? Following is the explanation taken from Java Language Specification – Section 3.3
The Java programming language specifies a standard way of transforming a program written in Unicode into ASCII that changes a program into a form that can be processed by ASCII-based tools. The transformation involves converting any Unicode escapes in the source text of the program to ASCII by adding an extra u
– for example, \uxxxx
becomes \uuxxxx
– while simultaneously converting non-ASCII characters in the source text to Unicode escapes containing a single u
each.
This post is really useful initially I also had no idea how to run java code within comment but after reading this post I really got the solution.
Hi,
Nice article about how to execute Java code within Java comments and easy to understand to java learners. Can yo explain about Is there a plan for Java 8 in Android?
Thanks,
Anjali,
Interesting information!