Java String getBytes() Method
Example
Convert a string into a byte array:
String myStr = "Hello";
byte[] result = myStr.getBytes();
System.out.println(result[0]);
Definition and Usage
The getBytes()
method converts a string into an array of bytes.
The encoding of the bytes depends on the charset argument.
If the charset argument is not provided then the bytes will be encoded using the system's default character set.
Syntax
One of the following:
public byte[] getBytes(Charset charset)
public byte[] getBytes()
Parameter Values
Parameter | Description |
---|---|
charset | Optional. A Charset object specifying which character set should be used when encoding the string as bytes. |
Technical Details
Returns: | A byte array representing the bytes of the string with a specific encoding. |
---|---|
Java version: | Any. charset parameter added in version 1.6. |
❮ String Methods