Convert String to Byte Array in Java using getBytes (encoding) Method


By using the 'getBytes()' function, one may convert a string into a byte array in the world of Java programming. The end result of this procedure is the acquisition of the starting string's representation as a byte array, with the method's specifications dictating the encoding. By using the 'getBytes()' function, there are two different ways to convert a string to a byte array in Java. The first strategy involves using the JVM's default charset encoding, which is an encoding technique. The second method depends on a specific charset encoding being supplied, with the requirements of the application in question determining the encoding to be used.

Within this discourse, we shall examine both of these approaches with great care, while also providing examples of code implementation and output for each approach.

Approaches used

This article discusses three different approaches to convert a string to a byte array in Java.

  • Approach 1 − The first approach involves using the default charset encoding. The `getBytes()` method is called on the string object with no encoding specified, resulting in the default charset encoding being used. This approach is suitable when no specific encoding is required for the conversion.

  • Approach 2 − The second approach involves using a specific charset encoding for the `getBytes()` method. This approach is useful when a different encoding is needed for the conversion than the default. The choice of encoding depends on the specific requirements of the application.

  • Approach 3 − The third approach uses the `ByteBuffer` class in Java. This class provides methods for converting a string to a byte array and vice versa. The `Charset` class is used to specify the encoding to be used for the conversion. This approach can be helpful when dealing with complex character encodings or when a more customizable conversion is needed.

The getBytes(encoding) method takes a string parameter, encoding, which specifies the character encoding scheme to be used. The method returns a byte array that represents the string in the specified encoding. The syntax of the method is as follows −

Syntax

byte[] byteArray = str.getBytes(encoding);

where str is the string to be converted, and encoding is the name of the encoding scheme.

Algorithm

To convert a string to a byte array in Java, you can follow these steps −

  • Step 1 − Obtain the string that you wish to convert to a byte array.

  • Step 2 − Decide on the encoding to be used for the conversion. If no encoding is specified, the default charset encoding will be utilized.

  • Step 3 − Invoke the `getBytes()` method on the string object and pass the encoding as an argument. This will return a byte array representation of the string.

  • Step 4 − Save the byte array in a variable for future use.

  • Step 5 − In the event that the specified encoding is not supported by the JVM, the `getBytes()` method will throw an `UnsupportedEncodingException`. You can handle this exception using a try-catch block.

  • Step 6 − Employ the `Arrays.toString()` method to print the byte array in a readable format.

  • Step 7 − If necessary, utilize the `new String(byteArray, encoding)` method to convert the byte array back to a string.

  • Step 8 − The converted byte array can now be used for further transmission or processing.

It is important to note that depending on the specific requirements of your application, additional steps or modifications may be necessary.

Approach 1

This approach to convert a string to a byte array in Java uses the default charset encoding, which is the encoding that the JVM uses by default. This approach is simple and straightforward, but it may not be suitable if the application requires a specific encoding.

Example

import java.util.Arrays;

public class StringToByteArray {
   public static void main(String[] args) {
      String str = "Hello, world!";
      byte[] byteArray = str.getBytes();
      System.out.println("Byte array using default charset encoding: " + Arrays.toString(byteArray));
   }
}

Output

Byte array using default charset encoding: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]

Approach 2

This approach to convert a string to a byte array in Java allows us to specify a specific charset encoding to be used. This gives us more control over the encoding used for the conversion and ensures that the byte array is compatible with the destination system.

Below is the program code for the same.

Example

import java.util.Arrays;
import java.io.UnsupportedEncodingException;

public class StringToByteArray {
   public static void main(String[] args) {
      String str = "Hello, world!";
      String encoding = "UTF-16";
      byte[] byteArray = null;
      try {
          byteArray = str.getBytes(encoding);
      } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
      }
      System.out.println("Byte array using " + encoding + " encoding: " + Arrays.toString(byteArray));
   }
}

Output

Byte array using UTF-16 encoding: [-2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 44, 0, 32, 0, 119, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33, 0]

In this output, we can see that the byte array contains an additional two bytes at the beginning (-2 and -1) when compared to the default encoding approach. These two bytes indicate the byte order of the UTF-16 encoding.

Approach 3

This approach to convert a string to a byte array in Java uses the ByteBuffer class to provide methods to convert a string to a byte array and vice versa. This approach is useful when we need to perform additional operations on the byte array using the methods provided by the ByteBuffer class.

Example

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;

public class StringToByteArray {
   public static void main(String[] args) {
      String str = "Hello, world!";
      Charset charset = Charset.forName("UTF-8");
      ByteBuffer byteBuffer = charset.encode(str);
      byte[] byteArray = byteBuffer.array();
      System.out.println("Byte array using ByteBuffer class: " + Arrays.toString(byteArray));
   }
}

Output

Byte array using ByteBuffer class: [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0]

Conclusion

To summarize, converting a string to a byte array in Java can be achieved through the 'getBytes()' method. There are two approaches, one using the default charset encoding and the other using a specific charset encoding. The choice of approach depends on the application's requirements. The 'ByteBuffer' class can also be used for this conversion, using the 'Charset' class to specify the encoding. We have provided detailed code examples and outputs for each approach.

Updated on: 18-Jul-2023

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements