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?

3
  • This is not a duplicate as the OP asks for a solution without StringBuffer.
    – Sweeper
    Nov 7, 2018 at 18:00
  • like this ____ : ) Nov 7, 2018 at 18:05
  • 5
    What emoji? If you mean e.g. 😀 'GRINNING FACE' (U+1F600), then write "😀" if your source code is UTF-8, or "\uD83D\uDE00" if not.
    – Andreas
    Nov 7, 2018 at 18:12

2 Answers 2

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

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
2
  • 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 7, 2018 at 18:19
  • 1
    Here's a online encoder/decoder that will generate the surrogate pairs when given an emoji and vice-versa: russellcottrell.com/greek/utilities/SurrogatePairCalculator.htm
    – Archie
    Aug 15, 2022 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.