Even though
new String(bytes, "UTF-8")
is correct it throws a UnsupportedEncodingException
which forces you to deal with a checked exception. You can use as an alternative another constructor since Java 1.6 to convert a byte array into a String
:
new String(bytes, StandardCharsets.UTF_8)
This one does not throw any exception.
Converting back should be also done with StandardCharsets.UTF_8
:
"test".getBytes(StandardCharsets.UTF_8)
Again you avoid having to deal with checked exceptions.