Introduction to StringUtils

StringUtils is the most used Apache Commons class. It contains various utilities and methods that help developers avoid writing boilerplate or simply unwieldy code for basic operations.

Many of the methods in the StringUtils class have their java.lang.String equivalents but, unlike the java.lang.String methods , are null-safe. This means that a NullPointerException is not thrown at the most unexpected moment.

Apache Commons contains a number of methods, and we'll look at some of the most commonly used.

List of StringUtils methods:

isEmpty() Checks if a string is empty
equals() Compares strings
compare() Compares strings
indexOf() Finding a substring in a string
lastIndexOf() Finding a substring in a string
contains() Checks if a substring is in a string
containsIgnoreCase() Checks for the occurrence of a substring in a string, ignoring case
containsAny() Checks if a substring occurs anywhere in a string
containsNone() Checks if a substring occurs anywhere in a string
containsOnly() Checks if a substring is in a string
substring() Getting a substring
split() Splitting a string into substrings
join() concatenate substrings
remove() Removing a substring
replace() Replace substring
countMatches() Counting the number of matches

StringUtils.isEmpty() and StringUtils.isBlank()

Both methods are used to check if a string contains any text. They return true if the string is really empty. Additionally, isBlank() will also return true if the string only contains spaces.

They also have their own inverse methods: isNotEmpty() and isNotBlank() .

Let's see how you can use isEmpty() along with its java.lang.String.isEmpty() counterpart , as well as isBlank() :

String nullValue = null;
String emptyValue = "";
String blankValue = "\n \t   \n";

if(StringUtils.isEmpty(emptyValue)) {
   System.out.println("emptyValue is emptyValue");
}

if(StringUtils.isBlank(blankValue)) {
   System.out.println("blankValue is blankValue");
}

if(!nullValue.isEmpty()) {
   System.out.println("nullString isn't null");
}

There are three variables of type String here . One points to null , the second is not null but has no content (an empty string), and the third is not empty but will print an empty result.

Running this code results in:

emptyValue is emptyValue
blankValue is blankValue
Exception in thread "main" java.lang.NullPointerException

The isEmpty() method built into java.lang.String is not null safe . You'll easily get a NullPointerException if you try to check if it's empty, because you call the method on a null reference . It will be necessary to check in advance whether the reference is null:

String nullValue = null;
String emptyValue = "";
String blankValue = "\n \t   \n";

if(StringUtils.isEmpty(emptyValue)) {
   System.out.println("emptyValue is emptyValue");
}

if(StringUtils.isBlank(blankValue)) {
   System.out.println("blankValue is blankValue");
}

if(nullValue != null && !nullValue.isEmpty()) {
   System.out.println("nullString isn't null");
}

Now this results in:

emptyValue is emptyValue
blankValue is blankValue

And if we test these methods onnullString:

String nullValue = null;

if(StringUtils.isEmpty(nullValue)) {
   System.out.println("nullValue is emptyValue");
}

if(StringUtils.isBlank(nullValue)) {
   System.out.println("nullValue is blankValue");
}

Then we get:

nullValue is emptyValue
nullValue is blankValue

The StringUtils methods are null safe and produce the expected result even if they are passed null .

StringUtils.equals()

This method compares two strings and returns true if they are identical or if both references point to null , but be aware that this method is case sensitive.

Let's see how it works:

System.out.println(StringUtils.equals(null, null));
System.out.println(StringUtils.equals(null, "some information"));
System.out.println(StringUtils.equals("some information", null));
System.out.println(StringUtils.equals("some information",  "some information"));
System.out.println(StringUtils.equals("some additional information", "some information"));

Result:

true
false
false
true
false

To compare the equals() method from StringUtils with java.lang.String.equals() :

String nullValue = null;

System.out.println(StringUtils.equals(nullValue, null));
System.out.println(StringUtils.equals(nullValue, "some information"));

System.out.println(nullValue.equals(null));
System.out.println(nullValue.equals("some information"));

This brings you back to:

true
false
Exception in thread "main" java.lang.NullPointerException

Again, calling a method on a null reference results in a NullPointerException , and you will need to check if the reference variable is null before using it.

StringUtils.compare()

The declaration of this method looks like this:

public static int compare(final String str1, final String str2)

This method compares two strings lexicographically, as the java.lang.String.compareTo() method does , returning:

  • 0 if str1 is equal to str2 (or both are null)
  • The value is less than 0 if str1 is less than str2
  • Value greater than 0 if str1 is greater than str2

The lexicographical order is the dictionary order. Let's see how we can use this in our program:

System.out.println(StringUtils.compare(null, null));
System.out.println(StringUtils.compare(null , "codeGym"));
System.out.println(StringUtils.compare("codeGym", null));
System.out.println(StringUtils.compare("codeGym", "CODEGYM"));
System.out.println(StringUtils.compare("codeGym", "codeGym"));

We get:

0
-1
1
32
0

Note: A null value is considered less than a non- null value . Two null values ​​are considered equal.

Checking if a string contains another substring

To do this, StringUtils has 5 methods:

  • contains()
  • containsIgnoreCase()
  • containsAny()
  • containsNone()
  • containsOnly()

The contains() method returns true or false depending on whether the search sequence is contained in another sequence or not.

If null is passed to such a method , it will return false . If non- null is passed , the method will simply call java.lang.String.indexOf(String str) on the passed object.

Examples:

String value = "CodeGym is cool";

System.out.println(StringUtils.contains(null, "a"));
System.out.println(StringUtils.contains(value, "CodeGym"));
System.out.println(StringUtils.contains(value, "C++"));
System.out.println(StringUtils.contains(value, "codegym"));

The method is case sensitive, so the last call will also return false :

false
true
false
false

The containsAny() method returns true if the string passed as the first argument contains at least one of the substrings passed in the 2-N arguments.

Example:

String value = "CodeGym is cool";
System.out.println(StringUtils.containsAny(value, "cool", "c00l", "bro", "hello"));

Will display:

true

This method is also case sensitive.

containsNone() method

When you need to check that a certain string does not contain anything from the list, you can use the containsNone() method . The first parameter is a string, and the following parameters are strings that should not be in the target sink.

Example:

String s = "CodeGym is cool";
System.out.println(StringUtils.containsNone(s, 'g', 'a'));

Console output:

false

Working with substrings

Working with substrings is similar to working with methods of the String class :

substring(String str, int start)
substring (String str, int start, int end)

These methods return a substring from the string str . The string is given by two indices: start and end . And as usual in Java, the last character of the range is end-1 . What is the advantage of these methods?

If you pass null to such a method , it will simply return null instead of throwing an exception. These methods support negative index values. In this case, the string is considered as a closed loop. The last character is followed by the first, and so on.

Let's see how we can use it:

System.out.println(StringUtils.substring("lets java", 2, 6));
System.out.println(StringUtils.substring("lets java", -8));
System.out.println(StringUtils.substring(null, 3));

Running the code above gives us:

ts j
ets java
null

StringUtils.split()

A method that allows you to split a string into substrings using a special delimiter character. If there is one in the target string, then the method will return an array of substrings. If there is no character, an empty array will be returned. Well, if null is passed to the method , it will return null . Let's take a look at this code and how the method works:

String myData = "Address, City, State, Zip, Phone, Email, Password";

System.out.println(Arrays.toString(StringUtils.split(myData, ',')));
System.out.println(Arrays.toString(StringUtils.split(null, '.')));
System.out.println(Arrays.toString(StringUtils.split("", '.')));

Result:

[Address,  City,  State,  Zip,  Phone,  Email,  Password]
null
[]

StringUtils.join()

The join() method allows you to concatenate an array of strings into a single string. At the same time, a special separator character can be passed to it, which will be added between substrings in the resulting string. And if null is passed to the method , then it will return null .

This method is the exact opposite of the split() method . Let's look at this simple example:

String myData = "Address, City, State, Zip, Phone, Email, Password";

String[] myString =  StringUtils.split(myData, ',');
System.out.println(StringUtils.join(myString, '-'));

Running the code above gives us:

Address- City- State- Zip- Phone- Email- Password

StringUtils.replace()

Searches for a string within a string, finds it if it exists, and replaces all occurrences of it with a new string.

The declaration of this method looks like this:

public static String replace(final String text, final String searchString, final String replacement)

If the search string is not found in the text, then nothing will happen and the text will remain the same. Following the same logic, if the text is null , this method returns null . If you are looking for a null string or replacing a substring with null , then the method will return the original string.

Let's try this method:

String value = "CodeGym is the best";
System.out.println(StringUtils.replace(value, "best", "cool"));

Result:

CodeGym is the cool
undefined
1
Task
Module 3. Java Professional, level 20, lesson 2
Locked
Nulls don't scare us
task4304
undefined
1
Task
Module 3. Java Professional, level 20, lesson 2
Locked
Going back to the origins
task4305