Our first program demonstrates base64 encoding and decoding. Here’s the full source code:
Java provides built-in support for base64 encoding/decoding through the java.util.Base64 class.
To run the program, compile and execute it using the javac and java commands:
The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.
In Java, we use the Base64.getEncoder() and Base64.getDecoder() for standard base64 encoding and decoding, and Base64.getUrlEncoder() and Base64.getUrlDecoder() for URL-safe base64 encoding and decoding.
The encodeToString() method is used to encode byte arrays to base64 strings, and decode() is used to decode base64 strings back to byte arrays. We convert between strings and byte arrays using String.getBytes() and the String constructor that takes a byte array.
Note that in Java, decoding an invalid base64 string will throw an IllegalArgumentException, which we catch in a try-catch block. This is different from the error handling approach used in the original example.