Open In App

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

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.

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:

Let us discuss how to convert a string into a byte array with the help of the given examples:

Example 1:




// 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); 
    
}
}

Output
String: Hello GeeksforGeeks
Result : 
-2-1072010101080108011103207101010101010701150102011101140710101010101070115

Example 2:




// 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); 
    
}
}

Output
String: Hello GFG
Byte Array:[72, 101, 108, 108, 111, 32, 71, 70, 71]

Article Tags :