In this article, you'll learn how to convert a byte[] array to a string in Java. We will also look at different ways to convert a string into a byte[] array. Conversion between byte array and string is one of the most common tasks in Java while reading files, generating crypto hashes, etc.

Convert Byte[] Array to String

1. Using String Constructor

The simplest way to convert a byte array to a string is to use the String class constructor with byte[] as an argument:

// create a byte array (demo purpose only)
byte[] bytes = "Hey, there!".getBytes();

// convert byte array to string
String str = new String(bytes);

// print string
System.out.println(str);

Here is the output of the above code snippet:

Hey, there!

By default, new String() uses the platform default character encoding to convert the byte array to a string. If the character encoding is different, you can specify it by passing another argument to new String() as shown below:

String str = new String(bytes, StandardCharsets.UTF_8);

2. Using Base64 Class

Since Java 8, we have Base64 class available that provides static methods for obtaining encoders and decoders for the Base64 encoding scheme. You can also use this class to encode byte array into a string as shown below:

// create a byte array (demo purpose only)
byte[] bytes = "Hey, there!".getBytes();

// convert byte array to string
String str = Base64.getEncoder().encodeToString(bytes);

// print string
System.out.println(str);

Convert String to Byte[] Array

1. Using String.getBytes() Method

To convert a string to a byte array, just use String.getBytes() method. This method uses the default character encoding to encode this string into a sequence of bytes. Here is an example:

// create a string (demo purpose only)
String str = "Hey, there!";

// convert string to byte array
byte[] bytes = str.getBytes();

You can also specify a different character encoding:

byte[] bytes = str.getBytes(StandardCharsets.UTF_8);

2. Using Base64 Class

The Base64 class can also be used to decode a string into a byte array as shown below:

// create a string (demo purpose only)
String str = "Hey, there!";

// convert string to byte array
byte[] bytes = Base64.getDecoder().decode(str);

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: