Convert String to Byte Array in Java Using getBytes(Charset) Method - GeeksforGeeks

28 Jan, 2021
In Java, strings are objects that are backed internally by a char array. So to convert a string to a byte array, we need a getBytes(Charset) method. This method converts the given string to a sequence of bytes using the given charset and returns an array of bytes. It is a predefined function of string class. Here, in this method we use an instance of Charset class, this class provides a named mapping between a sequence of the chars and a sequence of bytes. There are many charset defined and are discussed below.
US-ASCII: Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode character set
ISO-8859-1: ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
UTF-8: Eight-bit UCS Transformation Format
UTF-16BE: Sixteen-bit UCS Transformation Format, big-endian byte order
UTF-16LE: Sixteen-bit UCS Transformation Format, little-endian byte order
UTF-16: Sixteen-bit UCS Transformation Format, byte order identified by an optional byte-order mark.
Syntax:
public byte[] getBytes(Charset charset)
Parameter: This function takes one argument, that is the charset which is used to encode the string 
Return type: This function returns the resulting byte array. 
Note:
This method always replaces malformed input and unmappable character sequence with its charset’s default replacement byte array.
If the given charset is not a valid charset, then this method will throw UnsupportedEncodingException.
The length of the byte array is not the same as the given string, it depends upon the character encoding.
Let us discuss how to convert a string into a byte array with the help of the given examples:
Example 1:
Java
// Java program to illustrate how to// convert a string to byte array// Using getBytes(Charset charset)  import java.io.*;  class GFG{      public static void main (String[] args) {        // Initializing String     String ss = "Hello GeeksforGeeks";          // Display the string before conversion    System.out.println("String: " + ss);          try    {                 // Converting string to byte array        // Using getBytes(Charset charset) method        // Here, we converts into UTF-16 values        byte[] res = ss.getBytes("UTF-16");           // Displaying converted string after conversion         // into UTF-16         System.out.println("Result : ");                 for(int i = 0; i < res.length; i++)        {            System.out.print(res[i]);         }             }     catch (UnsupportedEncodingException g)     {        System.out.println("Unsupported character set" + g);     } }}
String: Hello GeeksforGeeks
Result : 
-2-1072010101080108011103207101010101010701150102011101140710101010101070115
Example 2:
Java
// Java program to illustrate how to// convert a string to byte array// Using getBytes(Charset charset)  import java.io.*;import java.util.Arrays;  class GFG{      public static void main (String[] args) {          // Initializing String     String ss = "Hello GFG";          // Display the string before conversion    System.out.println("String: " + ss);          try    {         // Converting string to byte array        // Using getBytes(Charset charset) method        // Here, we converts into US-ASCII values        byte[] res = ss.getBytes("US-ASCII");           // Displaying converted string after conversion         // into US-ASCII         System.out.println("Byte Array:" + Arrays.toString(res));    }         catch (UnsupportedEncodingException g)     {        System.out.println("Unsupported character set" + g);     } }}
String: Hello GFG
Byte Array:[72, 101, 108, 108, 111, 32, 71, 70, 71]

Java-Array-Programs
Java-Strings
Picked
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class