Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java Base64 Encode and Decode

  • Base64 encoding is a technique that enables the transmission of binary data over channels that are only intended to handle ASCII characters. It operates by transforming a string of binary data into an ASCII character set. This enables the secure transmission of binary data over channels that can only handle ASCII characters. To convert binary data to and from Base64-encoded ASCII strings, Java offers an integrated Base64 encoder and decoder.

  • To use the Base64 encoder and decoder in Java, you will need to import the java.util.Base64 class

Table Of Content

  • Java Base64 Encode and Decode
  • Basic Encoding and Decoding in java
  • URL Encoding and Decoding
  • MIME Encoding and Decoding in Java


  • To encrypt data at each level, this class provides three different encoders and decoders. At the following levels, these techniques are applicable.

  • 1.Basic Encoding and Decoding
  • 2.URL and Filename Encoding and Decoding
  • 3.MIME




Basic Encoding and Decoding

Encoding and decoding are processes of converting data from one format to another.Data that has been encoded is converted back into its original form after being transmitted or stored through the process of decoding. Data conversion into a format suitable for transmission or storage is known as encoding.


The American Standard Code for Information Interchange (ASCII), one of the most popular encoding methods, assigns numerical values to each character in the English alphabet as well as to other symbols and control characters.

As an example , in ASCII, the letter "A" is given the decimal value of 65 and the letter "a" is given the decimal value of 97.The entire ASCII character set can be found in a table, which shows the decimal value assigned to each character.


Encoding :

Suppose we want to encode the message "Hello, World!" in ASCII. We would first convert each character in the message to its corresponding ASCII value using the ASCII table. The resulting encoded message would be: 72 101 108 108 111 44 32 87 111 114 108 100 33.

Each number in this encoded message represents the ASCII value of the corresponding character in the original message.


Decoding :

To decode the encoded message back into its original form, we would simply convert each ASCII value back into its corresponding character using the ASCII table. The resulting decoded message would be: Hello, World!

By converting the ASCII values back into their corresponding characters, we have successfully decoded the original message.


Java Example of Basic Encoding and Decoding




public class AsciiEncodingDecoding {

    public static void main(String[] args) {
        
        String message = "Hello, World!";
        String encodedMessage = encodeAscii(message);
        String decodedMessage = decodeAscii(encodedMessage);
        
        System.out.println("Encoded message: " + encodedMessage);
        System.out.println("Decoded message: " + decodedMessage);
    }
    
    public static String encodeAscii(String message) {
        
        StringBuilder encodedMessage = new StringBuilder();
        
        for (int i = 0; i < message.length(); i++) {
            int asciiValue = (int) message.charAt(i);
            encodedMessage.append(asciiValue);
            if (i != message.length() - 1) {
                encodedMessage.append(" ");
            }
        }
        
        return encodedMessage.toString();
    }
    
    public static String decodeAscii(String encodedMessage) {
        
        String[] asciiValues = encodedMessage.split(" ");
        StringBuilder decodedMessage = new StringBuilder();
        
        for (String asciiValue : asciiValues) {
            int intValue = Integer.parseInt(asciiValue);
            char decodedChar = (char) intValue;
            decodedMessage.append(decodedChar);
        }
        
        return decodedMessage.toString();
    }
}

In this example We define two methods in this example, encodeAscii and decodeAscii, to handle the encoding and decoding of the message using ASCII. A string representation of the encoded message is returned by the encodeAscii method after converting each character in the input string message to its corresponding ASCII value. Decoding each ASCII value back into its corresponding character using the decodeAscii method results in a string representation of the decoded message.


In the main method, the message "Hello, World!" is encoded using the encodeAscii method.The decodeAscii method is then used to decode the message, and the outcomes are printed to the console.


There are numerous other libraries that can be used for data encoding and decoding in Java; this is just one example of how encoding and decoding can be implemented in Java.



Output:

Encoded message: 72 101 108 108 111 44 32 87 111 114 108 100 33
Decoded message: Hello, World! 



URL Encoding and Decoding

Java's Base64 class also supports URL-safe encoding and decoding, which replaces the '+' and '/' characters with '-' and '_' characters respectively. This is useful for encoding data that will be included in URLs or other web-related contexts.


To perform URL-safe encoding and decoding, you can use the following methods


Base64.getUrlEncoder().encodeToString(byte[] bytes) :

This method encodes a byte array into a URL-safe Base64-encoded string


Base64.getUrlDecoder().decode(String base64) :

This method decodes a URL-safe Base64-encoded string into a byte array


Java Example of Basic Encoding and Decoding
import java.util.Base64;

public class Base64Example {

public static void main(String[] args) {
    
    // Encode a string using URL-safe encoding
    String originalString = "https://www.dockertpoint.com/what-is-java.php;
    String encodedString = Base64.getUrlEncoder().encodeToString(originalString.getBytes());
    System.out.println("Encoded string: " + encodedString);
    
    // Decode a URL-safe encoded string
    byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedString);
    String decodedString = new String(decodedBytes);
    System.out.println("Decoded string: " + decodedString);
    
}

}

In this example, we first create a String object containing a URL. We then use the getBytes() method to convert this string into a byte array. Next, we encode the byte array using the Base64.getUrlEncoder().encodeToString() method and store the result in a new string called encodedString. We then print out the encoded string.


In the second part of the example, we decode the encoded string using the Base64.getUrlDecoder().decode() method. This method returns a byte array, which we then convert back into a string using the new String() constructor. Finally, we print out the decoded string.


As you can see, the encoded string is URL-safe and can be included in a URL without causing any issues.


Output:

Encoded string: aHR0cHM6Ly93d3cuZXhhbXBsZS5jb20vcGF0aC90by9yZXNvdXJjZT9wYXJhbT12YWx1ZQ==
Decoded string: https://www.dockertpoint.com/what-is-java.php
 




MIME Encoding and Decoding

Java's Base64 class also supports MIME encoding and decoding, which adds line breaks after every 76 characters and uses the characters '+' and '/' for encoding. This is useful for encoding data for email transmission, as MIME-encoded messages often have line length restrictions.


To perform MIME encoding and decoding, you can use the following methods


Base64.getMimeEncoder().encodeToString(byte[] bytes) :

This method encodes a byte array into a MIME Base64-encoded string


Base64.getMimeDecoder().decode(String base64) :

This method decodes a MIME Base64-encoded string into a byte array


Java Example of Basic Encoding and Decoding
import java.util.Base64;

public class Base64Example {

public static void main(String[] args) {
    
    // Encode a string using MIME encoding
    String originalString = "This is a long string that needs to be MIME-encoded to be transmitted via email";
    String encodedString = Base64.getMimeEncoder().encodeToString(originalString.getBytes());
    System.out.println("Encoded string: " + encodedString);
    
    // Decode a MIME-encoded string
    byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedString);
    String decodedString = new String(decodedBytes);
    System.out.println("Decoded string: " + decodedString);
    
}

}

In this example, we first create a String object containing a long message. We then use the getBytes() method to convert this string into a byte array. Next, we encode the byte array using the Base64.getMimeEncoder().encodeToString() method and store the result in a new string called encodedString. We then print out the encoded string.





In the second part of the example, we decode the encoded string using the Base64.getMimeDecoder().decode() method. This method returns a byte array, which we then convert back into a string using the new String() constructor. Finally, we print out the decoded string.


As you can see, the encoded string has line breaks after every 76 characters, as specified by the MIME standard.


Output:

Encoded string: VGhpcyBpcyBhIGxvbmcgc3RyaW5nIHRoYXQgbmVlZHMgdG8gYmUgTUlNRS1lbmNvZGVkIHR
vIGJlIHRyYW5zbWl0ZWQgdmlhIGVtYWlsICAgCnZpYSBlbmNvZGVkIHRvIHJlc3BvbnNlIHZpYQ==

Decoded string: This is a long string that needs to be MIME-encoded to be transmitted via email 

Java Default Method Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements
Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.