Our program demonstrates base64 encoding and decoding in Java. Here’s the full source code:
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-safe base64 encoders (trailing + vs -) but they both decode to the original string as desired.
In Java, we use the java.util.Base64 class for base64 encoding and decoding. This class provides separate encoders and decoders for standard and URL-safe base64 encoding schemes.
The Base64.getEncoder() and Base64.getDecoder() methods return encoders and decoders for the standard base64 encoding scheme, while Base64.getUrlEncoder() and Base64.getUrlDecoder() return encoders and decoders for the URL-safe variant.
When decoding, it’s a good practice to catch IllegalArgumentException as shown in the example, in case the input is not properly formatted base64 data.