Complete Guide to StringUtils in Java

Introduction

In this blog we will learn how to use StringUtils library in Java.

StringUtils is a part oF Apache commons lang library.

But why to choose ‘StringUtils’ over built-in ‘String’ class?

As a developer here are some reasons why you might choose to use StringUtils from Apache Commons Lang over the built-in String class in your project

  1. String Manipulation made easy: StringUtils offers a variety of simple methods for string manipulation that are not present in the standard String class. These include operations like truncating, padding, capitalization etc. You do not have to write your own methods and worry about bugs.

  2. Avoid NullPointerExcpetion: StringUtils provides methods to handle null values safely. You don’t have to worry about NullPointerException in your project. You can just relax.

  3. Whitespace Handling is super simple: StringUtils offers methods to manipulate whitespace in strings, such as removing leading and trailing spaces etc

  4. Providing Default Values: StringUtils allow you to provide default values in case a given string is null or empty, making code more readable.

  5. String Joining with Custom Delimiters: StringUtils offers methods for joining and splitting strings with custom delimiters or separators.

  6. Handling Empty/String Checks: StringUtils has methods to super convenient to check for empty, blank, or non-empty strings without having to write your own code.

  7. Abbreviation and Ellipsis: StringUtils offers convenient methods to abbreviate or add ellipses to strings, which can be useful for displaying truncated strings in our code.

Let’s get started!

We first need to add maven dependency for StringUtils from Apache commons library

1
2
3
4
5
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

StringUtils Methods

  1. StringUtils.isBlank This method checks if the provided string is null, has a length of 0, or consists only of whitespace characters. Here whitespace character is also considered blank
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.isBlank(""));   //true
        System.out.println(StringUtils.isBlank(" "));  //true. whitespace
        System.out.println(StringUtils.isBlank(null)); // true
        System.out.println(StringUtils.isBlank("Hello World")); //false 


    }
}
  1. StringUtils.isNotBlank

It returns true if the string is not null, its length is greater than 0, and it contains at least one character that is not a whitespace character.

This method is used in scenarios where we want to check if the string has content not just tab,spaces or line break.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.isNotBlank(null));  //false
        System.out.println(StringUtils.isNotBlank("")); //false
        System.out.println(StringUtils.isNotBlank(" ")); //false
        System.out.println(StringUtils.isNotBlank("Hello World"));  //true
        System.out.println(StringUtils.isNotBlank("\n")); //false
        System.out.println(StringUtils.isNotBlank(" \t")); //false


    }
}
  1. StringUtils.isEmpty()

This method checks if the provided string is null or has a length of 0. It considers a non-null, non-empty string as not empty.

Whitespace characters (spaces, tabs, line breaks) are considered as content, and a string containing only whitespace characters is not considered empty.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.isEmpty(null)); //true
        System.out.println(StringUtils.isEmpty("")); //true
        System.out.println(StringUtils.isEmpty(" ")); // false whitespace is content
        System.out.println(StringUtils.isEmpty("Hello World")); //false
        System.out.println(StringUtils.isEmpty("\n")); //false .new line is content
        System.out.println(StringUtils.isEmpty(" \t")); //false . tab is content


    }
}
  1. StringUtils.isNotEmpty()

This method checks if the provided string is not null or has a length greater than 0. It is just opposite of isEmpty() method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.isNotEmpty(null)); //false
        System.out.println(StringUtils.isNotEmpty("")); //false
        System.out.println(StringUtils.isNotEmpty(" ")); // true whitespace is content
        System.out.println(StringUtils.isNotEmpty("Hello World")); //true
        System.out.println(StringUtils.isNotEmpty("\n")); //true .new line is content
        System.out.println(StringUtils.isNotEmpty(" \t")); //true . tab is content


    }
}
  1. StringUtils.containsAny()

    containsAny() method checks if a given string contains any of the character in the given set. Character set to be tested can be passed as arguments to the method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.
                containsAny("Hello world","hel","wo")); //true
        System.out.println(StringUtils.
                containsAny("Hello world","zy","ab")); //false


    }
}
  1. StringUtils.countMatches()

This method provides you to count the number of occurences of a specified substring with a given string.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.
                countMatches("Hello world","l")); //3
        System.out.println(StringUtils.
                countMatches("Hello world","z")); //0

    }
}
  1. StringUtils.rotate()

This method rotates the string circularly by a given number of positions.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.
                rotate("Hello world",2)); // ldHello wor
        System.out.println(StringUtils.
                rotate("Hello world",3)); // rldHello wo



    }
}
  1. StringUtils.reverse()

This method reverses the characters in a given string.

It returns a new String in reverse order.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.
                reverse("Hello world")); // dlrow olleH

    }
}
  1. StringUtils.deleteWhitespace()

deleteWhitespace() method deleted whitespaces in the string and returns the string which is not having any whitespaces.

In the below example it deleted white spaces from any part of the string.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {

        System.out.println(StringUtils.deleteWhitespace("hello world")
                );  // helloworld
        System.out.println(StringUtils.deleteWhitespace("  hello world   ")
        );  // helloworld 
        System.out.println(StringUtils.deleteWhitespace("hello wor  ld  ")
        ); // helloworld

    }
}
  1. StringUtils.abbreviate()

The StringUtils.abbreviate method is used to abbreviate a string if it’s longer than a specified maximum length. This can be useful when you want to display a short version of a string while preserving its content.

If the string’s length exceeds the specified maximum length, it will be shortened and an ellipsis ("…") will be added to indicate that the string has been abbreviated.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {
        System.out.println(StringUtils.abbreviate("hello world is fine",14)); // hello world...


    }
}

You can add your own marker by specifying it in the argument as shown below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import org.apache.commons.lang3.StringUtils;

public class App {

    public static void main(String[] args) {
        System.out.println(StringUtils.abbreviate("hello world is fine","*",14));
       // hello world i*


    }
}
  1. StringUtils.join()

StringUtils.join() is used to concatenate elements of an array, collection into a single string, using a specified delimiter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class App {

    public static void main(String[] args) {

        // Join elements of an array using a delimiter
        String[] fruits = {"apple", "banana", "cherry"};
        String joinedArray = StringUtils.join(fruits, ", ");
        System.out.println("Joined array: " + joinedArray);

        // Join elements of a collection using a delimiter
        List<String> colors = new ArrayList<>(Arrays.asList("red", "green", "blue"));
        String joinedCollection = StringUtils.join(colors, " | ");
        System.out.println("Joined collection: " + joinedCollection);


    }
}

Output:

1
2
Joined array: apple, banana, cherry
Joined collection: red | green | blue