Java charAt used with characters that have two code units

前端 未结 4 728
梦毁少年i
梦毁少年i 2020-12-03 14:30

From Core Java, vol. 1, 9th ed., p. 69:

The character ℤ requires two code units in the UTF-16 encoding. Calling

String sentence =         


        
4条回答
  •  抹茶落季
    2020-12-03 14:37

    Horstmann was talking about the 'Z' which need two UTF-16 code units. Take a look at this code:

    public class Main {
        public static void main(String[] args)
        {
            String a = "\uD83D\uDE02 is String";
            System.out.println("Length: " + a.length());
            System.out.println(a.charAt(0));
            System.out.println(a.charAt(1));
            System.out.println(a.charAt(2));
            System.out.println(a.charAt(3));
        }
    }
    

    in IntelliJ Idea I can't even paste the 4 byte character as one character because while pasting this emoji:

提交回复
热议问题