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:

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 above function to get emoji flags for United States, United Kingdom, France and Germany:

System.out.println(countryCodeToEmoji("US")); // 🇺🇸
System.out.println(countryCodeToEmoji("UK")); // 🇬🇧
System.out.println(countryCodeToEmoji("FR")); // 🇫🇷
System.out.println(countryCodeToEmoji("DE")); // 🇩🇪

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.