String.getByte() Method in Java
getBytes() encodes a string into a sequence of bytes using the named character set and storing the result into a new byte array. This function can be implemented in two ways. Both the ways are discussed below as follows:
- getBytes(Charset charset)
Let us discuss and implement the first use-case that is as follows:
This function takes no arguments and used the default charset to encode the string into bytes. getbytes() function in java is used to convert a string into a sequence of bytes and returns an array of bytes.
public byte getBytes()
The String before conversion is : Geeks for Geeks The String after conversion is : 71101101107115321021111143271101101107115
Now let us implementation accepts the charset according to which string has to be encoded while conversion into bytes. There are many charset defined and are discussed below.
public byte getBytes(Charset charset);
- 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.
The String before conversion is : Geeks for Geeks The String after conversion into UTF-16 is : -2-107101010101010701150320102011101140320710101010101070115 The String after conversion into UTF-16BE is : 07101010101010701150320102011101140320710101010101070115
This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.