java.lang.String getBytes()

Description :

This java tutorial shows how to use the getBytes() method of java.lang.String class. This method returns byte[] array. The getBytes() method of String class generally convert or encode this String into byte array. This method accepts a Charset as parameter however if none is specified or unrecognizable input then the default will be used. If the input on the overriding method is a charsetName and its not recognized, a UnsupportedEncodingException will be thrown.

Method Syntax :

public byte[] getBytes()
public byte[] getBytes(Charset charset)
public byte[] getBytes(String charsetName)

Parameter Input :

Charset|charset|the charset to be used in converting or encoding the source String

Method Returns :

This method returns byte array (byte[]).

Exception :

public byte[] getBytes(String charsetName) throws UnsupportedEncodingException

UnsupportedEncodingException is thrown when the parameter charsetName is not on recognized.

Java Code Example :

This example source code demonstrates the use of getBytes() method of String class. Basically this source code just prints the byte array from the three method override of getBytes method. The code also shows the use of the Arrays.toString method to get the string representation of character array.

Sample Output :

Running the getBytes() method example source code of java.lang.String class will give you the following output

java string getbytes method example

java string getbytes method example

Exception Scenario :

Suggested Reading List :

References :