Languages
[Edit]
EN

Java - insert unicode character to string

0 points
Created by:
Jasmin
275

In this article, we would like to show you how to insert unicode character to string in Java.

There are three different ways how to do it:

  • with escape character e.g. \u03c0 that is equal to π,
  • by pasting character directly to string,
  • by converting codes to a string.

Quick solution:

public static void main(String[] args) throws Exception {
    String text = "π or \u03c0"; // U+03C0
    System.out.println(text);    // π or π
}

Output:

π or π

 

More complicated example

Space is represented by 0x20 (in hex) or 32 (in dec). It is necessary to add 2 additional zeros before code (e.g. \u0020).

public class Example {

    public static void main(String[] args) throws Exception {
        String text = "π and \u03c0 are\u0020equal"; // U+03C0 U+0020
        System.out.println(text);  // π and π are equal
    }
}

Output:

π and π are equal

Directly pasted emojis

In this section you can find some emojis that we pasted directly to the string and received e.g \uD83C\uDF4F for the 🍏 (green apple emoji).

public class Example {

    public static void main(String[] args) throws Exception {
        String apple = "\uD83C\uDF4F";
        String banana = "\uD83C\uDF4C";
        String cherry = "\uD83C\uDF52";
        
        System.out.println(apple);
        System.out.println(banana);
        System.out.println(cherry);
    }
}

Output:

🍏
🍌
🍒

Java - String (popular problems)

Java - insert unicode character to string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join