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 in Java
Convert a byte array to a string using a 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);
Convert a byte array to a string using the 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 in Java
Convert a string to a byte array using String.getBytes()
You can use the String.getBytes()
method to convert a string to a byte array. 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);
Convert a string to a byte array using the 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.