Java String - getBytes() Method
The Java getBytes() method is used to encode this String into a sequence of bytes using the given charset (or platform's default charset), storing the result into a new byte array.
Syntax
public byte[] getBytes() public byte[] getBytes(Charset charset) public byte[] getBytes(String charsetName) throws UnsupportedEncodingException
Parameters
charset |
Specify the Charset to be used to encode the String. |
charsetName |
Specify the name of a supported charset. |
Return Value
Returns the resultant byte array.
Exception
Throws UnsupportedEncodingException, If the named charset is not supported.
Example:
In the example below, getBytes() method is used to encode the given String into a sequence of bytes using the platform's default charset.
public class MyClass { public static void main(String[] args) { String MyString = "HELLO"; //encoding the string into a byte array byte Arr[] = MyString.getBytes(); //printing the content of byte array System.out.print("Default Charset encoding:"); for(byte i: Arr) System.out.print(" " + i); } }
The output of the above code will be:
Default Charset encoding: 72 69 76 76 79
Example:
In this example, the given String is encoded into a sequence of bytes using the given charset.
import java.nio.charset.Charset; public class MyClass { public static void main(String[] args) { String MyString = "HELLO"; //encoding the string into a byte array Charset cs = Charset.forName("UTF-16"); byte Arr[] = MyString.getBytes(cs); //printing the content of byte array System.out.print("UTF-16 Charset encoding:"); for(byte i: Arr) System.out.print(" " + i); } }
The output of the above code will be:
UTF-16 Charset encoding: -2 -1 0 72 0 69 0 76 0 76 0 79
Example:
Here, the given String is encoded into a sequence of bytes using the given charset string.
import java.io.*; public class MyClass { public static void main(String[] args) { String MyString = "HELLO"; try{ //encoding the string into a byte array String cs = "UTF-16BE"; byte Arr[] = MyString.getBytes(cs); //printing the content of byte array System.out.print("UTF-16BE Charset encoding:"); for(byte i: Arr) System.out.print(" " + i); }catch(UnsupportedEncodingException ex){ System.out.println("Unsupported character set"+ex); } } }
The output of the above code will be:
UTF-16BE Charset encoding: 0 72 0 69 0 76 0 76 0 79
❮ Java String Methods