Decode base64 string

This example will show how to decode a string containing an encoded Base64 string using java 8, guava and apache commons. Base64 is encoding scheme that take binary data and represents it as text. The term Base64 stems from a specific MIME content transfer encoding. A common use case to encoding binary date into characters is when you are sending it over the wire in hopes to prevent corruption.

Java 8

@Test
public void string_base64_decode_java_8()
        throws UnsupportedEncodingException {

    String encodedPhrase = "TGVhcm4uIEVhdC4gQ29kZS4=";

    byte[] decodedPhraseAsBytes = java.util.Base64.getDecoder().decode(
            encodedPhrase);

    String phraseDecodedToString = new String(decodedPhraseAsBytes, "utf-8");

    assertEquals("Learn. Eat. Code.", phraseDecodedToString);
}

Google Guava

@Test
public void string_base64_decode_guava() throws UnsupportedEncodingException {

    String encodedPhrase = "TGVhcm4uIEVhdC4gQ29kZS4=";
    
    byte[] decodedPhraseAsBytes = BaseEncoding.base64().decode(encodedPhrase);

    String phraseDecodedToString = new String(decodedPhraseAsBytes, "utf-8");
    
    assertEquals("Learn. Eat. Code.", phraseDecodedToString);
}

Apache Commons

@Test
public void string_base64_decode_apache() throws UnsupportedEncodingException {

    String encodedPhrase = "TGVhcm4uIEVhdC4gQ29kZS4=";
    
    byte[] decodedPhraseAsBytes = Base64.decode(encodedPhrase);

    String phraseDecodedToString = new String(decodedPhraseAsBytes, "utf-8");
    
    assertEquals("Learn. Eat. Code.", phraseDecodedToString);
}