Encoding & Decoding in Java

To encode in java use the below code:

import java.util.Base64;

public class Base64Encoder {
  public static void main(String[] args) {
    String input = "Hello, World!"; // The input string to encode

    // Encode the input string using Base64
    byte[] encodedBytes = Base64.getEncoder().encode(input.getBytes());

    // Print the encoded string
    String encodedString = new String(encodedBytes);
    System.out.println("Encoded string: " + encodedString);
  } 
}


To decode in java use the below code:

import java.util.Base64;

public class Base64Decoder {
    public static void main(String[] args) {
        String encodedString = "SGVsbG8sIFdvcmxkIQ=="; // The encoded string to decode

        // Decode the input string using Base64
        byte[] decodedBytes = Base64.getDecoder().decode(encodedString);

        // Convert the decoded bytes back to a string
        String decodedString = new String(decodedBytes);

        // Print the decoded string
        System.out.println("Decoded string: " + decodedString);
    } 

} 

Comments