# How to convert country code to emoji flag in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Aug 7, 2019, updated Oct 29, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/how-to-convert-country-code-to-emoji-in-java

> Learn about the easiest way to convert two letters country code into emoji flag in Java. 

Since Unicode characters are supported by all major browsers, you should consider using emojis instead of images for displaying countries' flags. Here is a little code snippet that converts country codes (ISO 3166-1 alpha-2) to corresponding emoji flags (Unicode regional indicator symbols) in Java:

```java
public String countryCodeToEmoji(String code) {

    // offset between uppercase ASCII and regional indicator symbols
    int OFFSET = 127397;

    // validate code
    if(code == null || code.length() != 2) {
        return "";
    }

    //fix for uk -> gb
    if (code.equalsIgnoreCase("uk")) {
        code = "gb";
    }

    // convert code to uppercase
    code = code.toUpperCase();

    StringBuilder emojiStr = new StringBuilder();

    //loop all characters
    for (int i = 0; i < code.length(); i++) {
        emojiStr.appendCodePoint(code.charAt(i) + OFFSET);
    }

    // return emoji
    return emojiStr.toString();
}
```

Let's use the above function to get emoji flags for the United States, United Kingdom, Germany, and Pakistan:

```java
System.out.println(countryCodeToEmoji("US")); // ??
System.out.println(countryCodeToEmoji("UK")); // ??
System.out.println(countryCodeToEmoji("DE")); // ??
System.out.println(countryCodeToEmoji("PK")); // ??
```
