This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: Why is “Hello World!” displayed after running this code? ?

Here’s some code I found online:

class M{public static void main(String [] a ‭){System.out.print(new char[]
{'H'.'e'.'l'.'l'.'o'.' '.'W'.'o'.'r'.'l'.'d'.'! '}); }}Copy the code

This code prints Hello World! On the screen; I can clearly see that public static void main is written down, but this is backwards. How does this code work? How to compile?

Edit: I tried this code in IntellIJ and it worked fine. However, for some reason, it doesn’t work with CMD in Notepad ++. I still haven’t found a solution, so if anyone does, please comment below.

Answer 1:

There are some invisible characters that change the way the code looks. In Intellij, they can be found by copying and pasting code into an empty string (” “), which replaces them with Unicode escapes, eliminating their effects and showing the order seen by the compiler.

Here is the output of the copy and paste:

"class M\u202E{public static void main(String[]a\u202D){System.out.print(new char[]\n"+
        "{'H','e','l','l','o',' ','W','o','r','l','d','! '}); }}"
Copy the code

Source code characters are stored in this order, and the compiler treats them as if they were stored in this order, but they are displayed differently.

Note that the \ u202E character is a right-to-left substitution, starting a block in which all characters are forced to display from right to left, while the \ u202D character, a left-to-right substitution, starts a nested block in which all characters are forced to line up from left to right, thus overriding the first override.

Thus, when it displays the original code, it will display the M class normally, but \ u202E will reverse the display order of everything to \ u202D, thus reversing everything again. (Normally, everything from \ u202D to the line terminator is reversed twice, once due to \ u202D and once due to \ u202E causing the rest of the text to be reversed, which is why this text appears in the middle of the line. Because of the line terminator, the orientation of the next line is independent of the orientation of the first line. So {‘H’, ‘e’, ‘l’, ‘l’, ‘O’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘! ‘}); }} Is displayed normally.