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.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.