Convert string to byte array in Java example shows how to convert string to a byte array using the getBytes
method of the String class using the UTF-8 encoding.
How to convert string to byte array in Java?
Use the getBytes
method of the String class to convert the string.
1 |
public byte[] getBytes() |
The getBytes
method encodes the string into bytes using the default character set of the platform and returns the byte array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.javacodeexamples.stringexamples; public class StringToByteArrayExample { public static void main(String[] args) { String str = "JavaCodeExamples"; /* * Convert String to byte array using * getBytes method of String class. */ byte[] byteArray = str.getBytes(); //print byte array System.out.println("Byte array: "); for(byte b : byteArray) System.out.print(b + ", "); } } |
Output
1 2 |
Byte array: 74, 97, 118, 97, 67, 111, 100, 101, 69, 120, 97, 109, 112, 108, 101, 115, |
Important Note:
If the string cannot be encoded in the platform’s default character set, the behavior of this method is unspecified. It is always suggested to specify character set while converting to avoid undesirable results.
How to encode the string to UTF-8 byte array?
As given in the above example, getBytes
method encodes the string to the default character set of the platform. It may produce undesirable results if the string cannot be converted to a byte array using the default character set. Use the getBytes
method which accepts the character set parameter while converting the string.
1 |
public byte[] getBytes(Charset charset) |
This method encodes the string to the given character set, stores the result in a byte array and returns it. It replaces malformed characters and characters which cannot be mapped in the target character set with the default replacement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javacodeexamples.stringexamples; import java.nio.charset.Charset; public class StringToByteArrayExample { public static void main(String[] args) { String str = "JavaCodeExamples"; byte[] byteArray = str.getBytes( Charset.forName("UTF-8") ); System.out.println("Byte array encoded in UTF-8: "); for(byte b : byteArray) System.out.print(b + ", "); } } |
Output
1 2 |
Byte array encoded in UTF-8: 74, 97, 118, 97, 67, 111, 100, 101, 69, 120, 97, 109, 112, 108, 101, 115, |
If you are using Java 7 or later version, you can use,
1 |
byte[] byteArray = str.getBytes( StandardCharsets.UTF_8 ); |
Instead of,
1 |
byte[] byteArray = str.getBytes( Charset.forName("UTF-8") ); |
This example is a part of the String in Java tutorial.
Please let me know your views in the comments section below.