Java Convert String to Byte Array

Tags: Byte Array

In this Java tutorial we learn how to convert a String value into a byte[] array in Java programming language.

Table of contents

  1. How to convert String to byte[] in Java
  2. Convert String to byte array and encode Base64 String

How to convert String to byte[] in Java

In Java we can get a byte[] array from a String using the String.getBytes() method.

String stringData = "Simple Solution";
byte[] byteData = stringData.getBytes(StandardCharsets.UTF_8);

The following example Java program to show you in detail how to use the String.getBytes() method to convert String to byte[] array.

StringToByteArrayExample1.java

import java.nio.charset.StandardCharsets;

public class StringToByteArrayExample1 {
    public static void main(String... args) {
        String stringData = "Simple Solution";

        // Convert String to Byte Array
        byte[] byteData = stringData.getBytes(StandardCharsets.UTF_8);

        System.out.println("\nString Data:" + stringData);
        System.out.println("Bytes Data:");
        for(byte b: byteData) {
            System.out.print(b);
        }
    }
}
The output as below.
String Data:Simple Solution
Bytes Data:
831051091121081013283111108117116105111110

Convert String to byte array and encode Base64 String

From the byte array of a String we can do a further step to encode it to the Base64 String as the following Java program

StringToByteArrayExample2.java

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class StringToByteArrayExample2 {
    public static void main(String... args) {
        String stringData = "Simple Solution";

        byte[] byteData = stringData.getBytes(StandardCharsets.UTF_8);

        String base64EncodedString = Base64.getEncoder().encodeToString(byteData);

        System.out.println("String Data:");
        System.out.println(stringData);
        System.out.println("Base64 String:");
        System.out.println(base64EncodedString);
    }
}
The output as below.
String Data:
Simple Solution
Base64 String:
U2ltcGxlIFNvbHV0aW9u

Happy Coding 😊

Java Convert Byte Array to String