StringUtils trimToNull() Example in Java

The StringUtils.trimToNull() method in Java is used to remove leading and trailing whitespaces from a string and return null if the resulting string is empty or null. In this post, we will see org.apache.commons.lang3.StringUtils trimToNull() example in Java. Here’s an example of how you can use it in Java.

import org.apache.commons.lang3.StringUtils;

public class StringUtilsTrimToNullExample {
    public static void main(String[] args) {
        String input = "   Trim this string   ";
        String trimmedString = StringUtils.trimToNull(input);
        if (trimmedString == null) {
            System.out.println("The input string is empty after trimming.");
        } else {
            System.out.println("Trimmed string: " + trimmedString);
        }
    }
}

Output – Trimmed string: Trim this string

Another example – StringUtils trimToNull() Example in Java

import org.apache.commons.lang3.StringUtils;

public class TrimToNullExample {

    public static void main(String[] args) {

        String str1 = "  Hello, World!  ";
        String str2 = "   ";
        String str3 = null;

        // Remove leading and trailing whitespaces and return null if the resulting string is empty or null
        String trimmedStr1 = StringUtils.trimToNull(str1);
        String trimmedStr2 = StringUtils.trimToNull(str2);
        String trimmedStr3 = StringUtils.trimToNull(str3);

        // Print the trimmed strings
        System.out.println(trimmedStr1);
        System.out.println(trimmedStr2);
        System.out.println(trimmedStr3);
    }
}

In this example, we import the org.apache.commons.lang3.StringUtils class and create three string variables str1, str2, and str3. We then call the StringUtils.trimToNull() method on each string variable and assign the results to new variables trimmedStr1, trimmedStr2, and trimmedStr3.

The StringUtils.trimToNull() method removes leading and trailing whitespaces from each string and returns null if the resulting string is empty or null. Finally, we print the trimmed strings to the console. The output should be:

Hello, World!
null
null

In this example, trimmedStr1 contains the trimmed string "Hello, World!", trimmedStr2 is null because the resulting string is empty after trimming, and trimmedStr3 is also null because the input string is null.

We need to add the below dependency in maven to use org.apache.commons.lang3.StringUtils wrap() method. We can download the apache-commons maven dependency from here.

pom.xml changes

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

see docs.

That’s all about StringUtils trimToNull() Example in Java.

Related post.