Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert an emoji in a Java string?

Tags:

java

string

emoji

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?

like image 682
2br-2b Avatar asked Nov 07 '18 17:11

2br-2b


2 Answers

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

like image 81
Rajat Avatar answered Oct 10 '22 14:10

Rajat


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
like image 23
syntagma Avatar answered Oct 10 '22 15:10

syntagma