Java String getBytes()Last Updated : 17 Mar 2025 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. ExampleCompile and RunOutput: 65 66 67 68 69 70 71 Java String class getBytes() Method Example 2The method returns a byte array that again can be passed to the String constructor to get String. ExampleCompile and RunOutput: 65 66 67 68 69 70 71 ABCDEFG Java String class getBytes() Method Example 3The following example shows the encoding into a different charset. Output: The input String is : Welcome to TpointTech. 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. ExampleCompile and RunOutput:
/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 request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India