Convert String to Byte Array in Java using getBytes (Charset) method


Java programming involves the conversion of String to byte array, a handy technique for a multitude of purposes including network communication or data encryption. To achieve this, the String class provides an array of methods for such conversion, with the getBytes() method being one of them. It is crucial to note that choosing the appropriate encoding is crucial since each encoding utilizes different regulations when it comes to character to byte value mapping.

In this article, we will delve into two techniques for converting a String to a byte array using Java's getBytes() method. Additionally, we will provide an extensive explication of the algorithm employed by each of these methods.

Approaches used

  • Approach 1 − In this approach, we will create a String and then convert it to a byte array using the getBytes() method. We will use the UTF-8 encoding for this example.

  • Approach 2 − In this approach, we will create a byte array by manually specifying the byte values. We will then use the String constructor to create a String from the byte array.

Syntax

The getBytes() method is a member of the String class in Java. It takes a single argument, which is the charset to be used for encoding the String into a byte array. The syntax of the getBytes() method is as follows −

public byte[] getBytes(Charset charset)

Algorithm

The methodology for converting a String into a byte array in Java by utilizing the getBytes() function can be distilled into a few steps −

  • Step 1 − Instantiate a Charset object that corresponds to the desired encoding, using the forName() method from the Charset class. This step entails providing the name of the encoding as a string argument.

  • Step 2 − Invoke the getBytes() method of the String class, while feeding the previously created Charset object as an argument. This call produces the byte array that represents the characters within the String by using the specified encoding.

  • Step 3 − Manipulate the resulting byte array as needed. Java offers various techniques for working with the byte array through its programming language.

Utilizing the getBytes() function is a potent approach for converting Strings into byte arrays in Java. It enables you to specify the encoding to be used during the conversion process. It is crucial since different encodings possess distinct guidelines for mapping characters into byte values. By using the wrong encoding, data corruption might occur. By following the above algorithm, one can ensure that their String will be successfully and safely converted into a byte array..

Approach 1

In this approach, we began by creating a String that we wished to convert to a byte array. Then, we utilized the getBytes() method of the String class to transform the String to a byte array. We defined the encoding that we wanted to apply for the conversion, which was UTF-8 in this instance. To ensure that the byte array was generated accurately, we printed it out.

Below is the program code for the same.

Example

import java.nio.charset.Charset;

public class StringToByteArrayExample1 {
   public static void main(String[] args) {
      // Create a String
      String str = "Hello, world!";
        
      // Convert the String to a byte array using the UTF-8 encoding
      Charset utf8 = Charset.forName("UTF-8");
      byte[] byteArray = str.getBytes(utf8);
       
      // Print the byte array
      for (byte b : byteArray) {
         System.out.print(b + " ");
      }
   }
}

Output

72 101 108 108 111 44 32 119 111 114 108 100 33

Approach 2

This method included manually entering the byte values to construct a byte array. The byte array was then converted into a String using the String constructor.

Below is the program code for the same.

Example

import java.nio.charset.Charset;

public class StringToByteArrayExample2 {
   public static void main(String[] args) {
      // Create a byte array
      byte[] byteArray = {72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33};
        
      // Convert the byte array to a String using the UTF-8 encoding
      Charset utf8 = Charset.forName("UTF-8");
      String str = new String(byteArray, utf8);
        
      // Print the String
      System.out.println(str);
   }
}

Output

Hello, world!

Conclusion

The containsKey() function, used to determine if a certain key is contained in a hashmap or not, was covered in this article. This method accepts a key as an input and, if the key is found in the hashmap, returns true; otherwise, it returns false.

Updated on: 18-Jul-2023

74 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements