Why does a keyboard-entered super Unicode string change after being passed to a method?

47 views Asked by At

Why is the string "Hello" entered by Scanner(System.in) printed incorrectly after calling func(str2)?

The java code is as follows:

package test;
import java.util.Scanner;

public class TestCodePoint
{
    private static void func(String str)
    {
        System.out.println("after: " + str);
    }

    public static void main(String[] args)
    {
        String str = "Hello";
        System.out.println("before: " + str);
        func(str);
        System.out.print("Please input a string: ");
        Scanner sc = new Scanner(System.in);
        String str2 = sc.next();
        System.out.println("str2_before: " + str);
        func(str2);
    }
}

The result of the implementation is:

before: Hello
after: Hello
Please input a string: Hello   (Here is the paste input)
str2_before: Hello
after: ��Hello

Why is the output of the last one "��Hello" instead of "Hello"?

0

There are 0 answers