Java String getBytes()
The Java String class getBytes() method does the encoding of string into the sequence of bytes and keeps it in an array of bytes.
Signature
There are three variants of getBytes() method. The signature or syntax of string getBytes() method is given below:
Parameters
charset / charsetName – The name of a charset the method supports.
Returns
Sequence of bytes.
Exception Throws
UnsupportedEncodingException: It is thrown when the mentioned charset is not supported by the method.
Internal implementation
String class getBytes() Method Example
The parameterless getBytes() method encodes the string using the default charset of the platform, which is UTF – 8. The following two examples show the same.
FileName: StringGetBytesExample.java
Output:
65 66 67 68 69 70 71
Java String class getBytes() Method Example 2
FileName: StringGetBytesExample2.java
The method returns a byte array that again can be passed to the String constructor to get String.
Output:
65 66 67 68 69 70 71 ABCDEFG
Java String class getBytes() Method Example 3
The following example shows the encoding into a different charset.
FileName: StringGetBytesExample3.java
Output:
The input String is : Welcome to TutorAspire . After converted into UTF-16 the String is : -2-10870101010809901110109010103201160111032074097011809708401120111010501100116046 After converted into UTF-16BE the String is : 0870101010809901110109010103201160111032074097011809708401120111010501100116046 After converted into ISO-8859-1 the String is : 871011089911110910132116111327497118978411211110511011646 After converted into UTF-16LE the String is : 8701010108099011101090101032011601110320740970118097084011201110105011001160460
Java String class getBytes() Method Example 4
The following example shows when the charset is not supported by the getBytes() method, UnsupportedEncodingException is thrown.
FileName: StringGetBytesExample4.java
Output:
/StringGetBytesExample4.java:11: error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown byte[] byteArr = str.getBytes("UTF-17"); ^ 1 error