Java String: getBytes() Method
getBytes() Method
Contents:
public byte[] getBytes()
The getBytes() method is used to encode a specified String into a sequence of bytes using the named charset, storing the result into a new byte array.
The behavior of this method, when this string cannot be encoded in the given charset, is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
Java Platform: Java SE 8
Syntax:
getBytes()
Return Value:
The resultant byte array.
Return Value Type:
Example: Java String getBytes() Method
The following example shows the usage of java String() method.
Output:
The new String is : The quick brown fox jumps over the lazy dog.
public byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
This method always replaces malformed-input and unmappable-character sequences with this charset's default replacement byte array. The CharsetEncoder class should be used when more control over the encoding process is required.
Syntax:
getBytes(Charset charset)
Parameters:
Name | Description | Type |
---|---|---|
charset | The Charset to be used to encode the String. | byte |
Return Value : The resultant byte array.
Return Value Type: byte
Example: Java String getBytes(Charset charset) Method
The following example shows the usage of java String() method.
Output:
Original string = example.com New string = example.com
public byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
The behavior of this method, when this string cannot be encoded in the given charset, is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
Syntax:
getBytes(String charsetName)
Parameters:
Name | Description | Type |
---|---|---|
charsetName | The name of a supported charset. | byte |
Return Value: The resultant byte array.
Return Type: byte
Throws:
UnsupportedEncodingException - If the named charset is not supported
Example: Java String getBytes(String charsetName) Method
The following example shows the usage of java String() method.
Output:
Original string = example.com New string = example.com
Java Code Editor:
Previous:format Method
Next:getChars Method