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. SignatureThere are three variants of getBytes() method. The signature or syntax of string getBytes() method is given below: Parameterscharset / charsetName - The name of a charset the method supports. ReturnsSequence of bytes. Exception ThrowsUnsupportedEncodingException: It is thrown when the mentioned charset is not supported by the method. Internal implementationString class getBytes() Method ExampleThe 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 Test it NowOutput: 65 66 67 68 69 70 71 Java String class getBytes() Method Example 2FileName: StringGetBytesExample2.java The method returns a byte array that again can be passed to the String constructor to get String. Test it NowOutput: 65 66 67 68 69 70 71 ABCDEFG Java String class getBytes() Method Example 3The following example shows the encoding into a different charset. FileName: StringGetBytesExample3.java Output: The input String is : Welcome to JavaTpoint. 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 4The 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 Next TopicJava String getChars() |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India