Java program to convert string to byte array and byte array to string

Java program to convert String to byte array and Byte array to String :

In this tutorial, we will learn how to convert string to byte array and byte array back to a string. Converting a string to a byte array is useful in many cases like IO operations.

Convert String to a byte array :

We can convert any sting using its built in method ‘getBytes()‘. It returns an array of bytes.

 public static void main(String[] args) {
        String myString = "Hello World!";

        byte[] myByte = myString.getBytes();

    }

In this example, ‘myByte’ variable contains an array of bytes for the string ‘Hello World!’ . Let’s try to convert this byte array back to a string :

Converting a byte array to String :

Converting a byte array to a string can be done by using ‘String’ constructor like below :

public class Main {

    /**
     * Utility function to print a line
     *
     * @param line : line to print
     */
    static void print(String line) {
        System.out.println(line);
    }

    public static void main(String[] args) {
        String myString = "Hello World!";

        byte[] myByte = myString.getBytes();

        print("Converted string using String constructor "+new String(myByte));
    }
}

Output :

Converted string using String constructor Hello World!

Conversion of String to byte array using encoding :

One byte contains 8 bits. So, it can contain 256 different values. ASCII character set contains 128 different characters. But for non ASCII characters, we can specify one encoding scheme that produces encoded bytes. Using same decoding scheme, we can decode the encoded byte to the original String :

import java.nio.charset.StandardCharsets;

public class Main {

    /**
     * Utility function to print a line
     *
     * @param line : line to print
     */
    static void print(String line) {
        System.out.println(line);
    }

    public static void main(String[] args) {
        String myString = "Hello World!";

        byte[] myByte = myString.getBytes(StandardCharsets.UTF_8);

        print("Converted string using String constructor "+new String(myByte,StandardCharsets.UTF_8));
    }
}

Output :

Converted string using String constructor Hello World!

Similar tutorials :