Why isn't Java properly displaying unicode in the String?

Viewed 730

I am using IntelliJ IDEA and I was trying to print a string that has unicode for a skier U+26F7 and for a runner U+1F3C3 with the following code:

System.out.println("\u26f7" + "   " + "\u1f3c3");

Only the skier displays properly. However, IntelliJ does show the last 3 of the runner code with different color, indicating that there was a problem. Any ideas on how to fix this?

2 Answers

Java uses utf16 so the character \u1f3c3 is out of its range. You can pass in the character using it's surroget pair

System.out.println("\u26f7" + "   " + "\ud83c\udfc3")

Java’s escape syntax was designed back when Unicode was expected to have no more than 216 characters, so you must specify exactly four hex digits ater the \u. No more, no less.

"\u1f3c3" is actually the two characters \u1f3c and 3.

Java Strings are always in UTF-16. So one option is to look up detailed information for your character (for instance, here) and use the corresponding UTF-16 values in your string: 0xD83C 0xDFC3 → "\uD83C\uDFC3"

Another option is using the %c specifier in java.util.Formatter. For example:

System.out.printf("%c   %c%n", 0x26f7, 0x1f3c3);

(Unlike println, printf does not print a newline unless you add %n to the format.)

Related