Unicode escape problem in JAVA

         I read an interesting piece of code last night, and today I checked the relevant knowledge on the Internet. It is called unicode escape phenomenon on the Internet. Let’s take a look at what’s going on. Without further ado, let’s get into the code.

package com.lsl.exam.utils;

public class MyTest {

    /**
     * unicode逃逸
     * 有意思的注释
     */
    public static void test1(){

        if (true == false){

            //注释
            // \u000a\u007d\u007b
            System.err.println("true is false");
        }

        String str = "坏人";//\u000d str="好人";
        System.err.println("我是" + str);

    }

    public static void main(String[] args) {
        test1();
    }
}

The code is very simple, let’s take a guess:

        Was the first output statement executed?

        What does the second output statement output?

The execution result is as follows:

Is the execution result a bit unexpected? What is the reason for this result? The key lies in this comment, which is the phenomenon of unicode escape.

        We know that the java compiler will compile the code. In addition, the compiler will also parse the unicode code, and \u000a is a line feed and \u000d is a carriage return. \u007d is the left curly brace {, \u007b is the right curly brace} . Then the code finally becomes as follows:

package com.lsl.exam.utils;

public class MyTest {

    /**
     * unicode逃逸
     * 有意思的注释
     */
    public static void test1(){

        if (true == false) {

            //注释
            //
        }{
            System.err.println("true is false");
        }

        String str = "坏人";//
        str="好人";
        System.err.println("我是" + str);

    }

    public static void main(String[] args) {
        test1();
    }
}

     This is the code unicode escape phenomenon.

Please do not try to write such comments in your code, you will easily get beaten.

Guess you like

Origin blog.csdn.net/dhklsl/article/details/132824815