Java String getBytes() method example

HQ » Java Tutorial » java.lang » String » getBytes() method example
Java String getBytes() method example 2018-02-19T12:50:41+00:00

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 :

DataType Parameter Description
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 :

 

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close