10

I am trying to make a program which prints out emoji. However, it won't let me insert an emoji in the SDK, and the \u doesn't allow for enough characters to use an emoji. Is there any simple way to do this?

All of the online solutions seem to refer to a StringBuffer. Is there any way to do this without a StringBuffer? If not, how would I use this?

syntagma
  • 23,346
  • 16
  • 78
  • 134
2br-2b
  • 395
  • 2
  • 5
  • 13

2 Answers2

14

If you are looking for sending server-side notifications using SNS then following works

String context = "You can eat water too! ";
        context += new String(Character.toChars(0x1F349));

various emoji unicodes

Rajat
  • 2,467
  • 2
  • 29
  • 38
6

It can be done, without using StringBuilder, with Unicode surrogate pair:

Surrogate characters are typically referred to as surrogate pairs. They are the combination of two characters, containing a single code point. To make the detection of surrogate pairs easy, the Unicode standard has reserved the range from U+D800 to U+DFFF for the use of UTF-16. No characters are assigned to code point values in this range. When programs see a bit sequence that falls in this range, they immediately—zip! zip!—know that they have encountered a surrogate pair.

This reserved range is composed of two parts:

  • High surrogates — U+D800 to U+DBFF (total of 1,024 code points)
  • Low surrogates — U+DC00 to U+DFFF (total of 1,024 code points)

The following would print extraterrestrial alien emoji ():

int[] surrogates = {0xD83D, 0xDC7D};
String alienEmojiString = new String(surrogates, 0, surrogates.length);
System.out.println(alienEmojiString);
System.out.println("\uD83D\uDC7D");   // alternative way
syntagma
  • 23,346
  • 16
  • 78
  • 134
  • 9
    I think this would be a better answer if it included a quick explanation of what UTF-16 is, why Java Strings require it, and why is expressed as `\uD83D\uDC7D`. – VGR Nov 07 '18 at 18:19
  • 1
    Here's a online encoder/decoder that will generate the surrogate pairs when given an emoji and vice-versa: http://russellcottrell.com/greek/utilities/SurrogatePairCalculator.htm – Archie Aug 15 '22 at 18:02