Edit: Andrey's answer has been updated, so it no longer applies.
Andrey's answer (the highest that was voted at the time of writing) is a bit incorrect. I would add this as a comment, but I'm not authoritative enough.
In response, Andrew:
char[] chars = {'c', 'h', 'a', 'r', 's'} byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars)).array();
calling array () may not return the required value, for example:
char[] c = "aaaaaaaaaa".toCharArray(); System.out.println(Arrays.toString(Charset.forName("UTF-8").encode(CharBuffer.wrap(c)).array()));
exit:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0]
As you can see, zero byte is added. To avoid this, use the following:
char[] c = "aaaaaaaaaa".toCharArray(); ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c)); byte[] b = new byte[bb.remaining()]; bb.get(b); System.out.println(Arrays.toString(b));
exit:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97]
As the answer also referred to the use of passwords, this might be worth the blanking of an array that supports ByteBuffer (access via array ()):
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c)); byte[] b = new byte[bb.remaining()]; bb.get(b); blankOutByteArray(bb.array()); System.out.println(Arrays.toString(b));