To create a string from a byte array in Java, you can use the String
constructor that takes a byte array and an encoding as arguments. Here's an example:
byte[] bytes = {'h', 'e', 'l', 'l', 'o'}; String s = new String(bytes, StandardCharsets.UTF_8);
The encoding specifies how the bytes in the array should be interpreted as characters. In this example, we're using the UTF-8
encoding, which is a widely used character encoding that can represent most of the characters in the Unicode character set.
You can also use other character encodings such as ASCII
, ISO-8859-1
, or UTF-16
. It's important to use the same encoding when converting a string to a byte array as when converting the byte array back to a string, to ensure that the resulting string is the same as the original.
Here's an example of how to convert a string to a byte array and back again using the UTF-16
encoding:
String s = "hello"; byte[] bytes = s.getBytes(StandardCharsets.UTF_16); String s2 = new String(bytes, StandardCharsets.UTF_16);
Note that the getBytes
method of the String
class returns a byte array that represents the string using the default platform encoding. It's generally recommended to specify the encoding explicitly, as shown in the examples above.