Base64 Encoding in Logo
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 to perform 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.
Note that in Java, we need to convert our String to a byte array using getBytes()
before encoding, and we need to create a new String from the decoded byte array to get the original string back.
Also, unlike in some other languages, Java’s base64 decoder throws an IllegalArgumentException
if the input is not properly encoded. It’s a good practice to catch this exception when decoding data from an untrusted source.