Open In App

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

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To convert a string to a byte array, we use the getBytes(Charset) method In Java that transforms the string into a sequence of bytes based on a specified character encoding. This method returns the byte array and relies on the Charset class to handle character-to-byte mappings.

Example:

Java
// Java program to convert a String to a byte array 
// using getBytes(Charset) method with UTF-8 encoding
import java.nio.charset.StandardCharsets;

public class StringToByteArray {
  
    public static void main(String[] args) {
        
        // sample string
        String s = "hello";

        // Convert string to byte array using UTF-8 encoding
        byte[] b = s.getBytes(StandardCharsets.UTF_8);

        // Print the byte array
        for (byte b1 : b) {
            System.out.print(b1 + " ");
        }
    }
}

Output
104 101 108 108 111 

Explanation: The above program converts the string “hello” into a byte array using UTF-8 encoding by using the getBytes(StandardCharsets.UTF_8) method. Then it prints each byte of the resulting byte array.

Syntax of getBytes(Charset) Method

byte[] byteArray = string.getBytes(Charset charset);

Parameter: charset is the character set used to encode the string. For example, StandardCharsets.UTF_8 or Charset.forName("UTF-8").

Return type: This function returns the resulting byte array. 

Important Points:

  • 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.

Other Ways to Convert a String to Byte Array Using getBytes(Charset)

1. Convert String to Byte Array Using UTF-16 Charset

Example:

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) {
        String s = "Hello GeeksforGeeks";

        // Display the string before conversion
        System.out.println("String: " + s);

        try {
            // Converting string to byte array
            // Using getBytes(Charset charset) method
            // Here, we convert the string into UTF-16 values
            byte[] r = s.getBytes("UTF-16");

            // Displaying the converted string after 
            // conversion into UTF-16
            System.out.println("Result: ");
            for (int i = 0; i < r.length; i++) {
                System.out.print(r[i] + " ");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

Output
String: Hello GeeksforGeeks
Result: 
-2 -1 0 72 0 101 0 108 0 108 0 111 0 32 0 71 0 101 0 101 0 107 0 115 0 102 0 111 0 114 0 71 0 101 0 101 0 107 0 115 

Explanation: The above example converts the string "Hello GeeksforGeeks" into a byte array using the UTF-16 charset with the getBytes("UTF-16") method. Then it prints each byte of the resulting byte array to the console.

2. Convert String to Byte Array Using US-ASCII Charset

Example:

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) 
{
    
    String s1 = "Hello GFG";
    
    // Display the string before conversion
    System.out.println("String: " + s1);
    
    try
    { 
        // Converting string to byte array
        // Using getBytes(Charset charset) method
        // Here, we converts into US-ASCII values
        byte[] r = s1.getBytes("US-ASCII"); 

        // Displaying converted string after conversion 
        // into US-ASCII 
        System.out.println("Byte Array: " + Arrays.toString(r));
    } 
  
    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]

Explanation: The above example converts the string "Hello GFG" into a byte array using the US-ASCII charset with the getBytes("US-ASCII") method. Then it prints the resulting byte array using Arrays.toString() to display the ASCII values of the characters.



Next Article

Similar Reads