In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getBytes(Charset) method. This method converts the given string to a sequence of bytes using the given charset and returns an array of bytes. It is a predefined function of string class. Here, in this method we use an instance of Charset class, this class provides a named mapping between a sequence of the chars and a sequence of bytes. There are many charset defined and are discussed below.
- US-ASCII: Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
- ISO-8859-1: ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
- UTF-8: Eight-bit UCS Transformation Format
- UTF-16BE: Sixteen-bit UCS Transformation Format, big-endian byte order
- UTF-16LE: Sixteen-bit UCS Transformation Format, little-endian byte order
- UTF-16: Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark.
public byte getBytes(Charset charset)
Parameter: This function takes one argument, that is the charset which is used to encode the string
Return type: This function returns the resulting byte array.
- This method always replaces malformed input and unmappable character sequence with its charset’s default replacement byte array.
- If the given charset is not a valid charset, then this method will throw UnsupportedEncodingException.
- The length of the byte array is not the same as the given string, it depends upon the character encoding.
Let us discuss how to convert a string into a byte array with the help of the given examples:
String: Hello GeeksforGeeks Result : -2-1072010101080108011103207101010101010701150102011101140710101010101070115
String: Hello GFG Byte Array:[72, 101, 108, 108, 111, 32, 71, 70, 71]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.