What is StringUtils.getBytes in Java?

getBytes is a static method of the StringUtils class that is used to convert the given string to a byte array for a given character set in a null-safe manner.

  • If no character set is given, then the default character set is used.
  • The method returns an empty byte array if the passed string is null.
  • If the passed string is not null, then the method will return the output of the getBytes() method of the String class.

How to import StringUtils

StringUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml file.

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the StringUtils class as follows.

import org.apache.commons.lang3.StringUtils;

Syntax


public static byte[] getBytes(String string, Charset charset)

Parameters

  • String string: string to convert to bytes.
  • Charset charset: Character set to encode the string with.

Return value

The method returns an empty byte array if the passed string is null. Otherwise the method returns the output of String.getBytes(Charset).

Code

import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String s = "educative";
System.out.println("Byte array for the string 'educative' is - " + Arrays.toString(StringUtils.getBytes(s, StandardCharsets.UTF_8)));
System.out.println("Byte array for a null string is - " + Arrays.toString(StringUtils.getBytes(null, StandardCharsets.UTF_8)));
}
}

Expected output


Byte array for the string 'educative' is - [101, 100, 117, 99, 97, 116, 105, 118, 101]
Byte array for a null string is - []

Explanation

  • educative string

The output of the method when the string above is passed is [101, 100, 117, 99, 97, 116, 105, 118, 101]. The byte array is returned as the string is not null.

  • null string

The output of the method when the string above is passed is []. An empty byte array is returned as the string is null.

Free Resources