Home » Java programming language

Run code in comments in Java



In this article, we will discuss about a simple trick in java to run code written in comments.
Submitted by Aman Gautam, on January 01, 2018

We have studied that comments never executes, but there is a trick by which we can mock the friends by showing them a code runs i.e. written in comments. This can be done using a Unicode character because java parse character escape sequence in the source code. So for this we used,

/u000d → Unicode character, parsed as new line '\n' by java.

Here is a program for the same,

public class codeInComment {
	public static void main(String[] args) {
		System.out.println("This program will run code in comments");
		//this is a simple comment
		//test \u000d System.out.println("this is a comment");
	}
}

Output

This program will run code in comments
this is a comment

The above program will be treated as,

public class codeInComment {
	public static void main(String[] args) {
		System.out.println("This program will run code in comments");
		//this is a simple comment
		// test
		System.out.println("this is a comment");
	}
}

Note: this will only work for single line comments.

The following multiline comment

/* \u000d System.out.println("this is a comment");
 */

will not work because it will be treated as

/*
System.out.println("this is a comment");
 */

So nothing will get printed.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.