StringUtils defaultIfBlank() Method

StringUtils defaultIfBlank() Method | The defaulIfBlank() method of StringUtils class returns the given set of strings if the passed string is null or else if the string is not null it returns the original string only. This is one of the best ways to replace the null string.

StringUtils.defaultIfBlank() Method in Java

The syntax for the method defalulIfBlank is as follows:
public static T defaultIfBlank(final T str, final T defaultStr)
It returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null, the value of defaultStr.
Parameters:
str: the string which will be checked whether it is blank or not.
defaultStr: the string which will be replaced if the other string is blank.
Return type: string.
Returns: It either returns the given default value if the string is null or if the string is not null then returns the string.

Java StringUtils defaultIfBlank() Method Example

import org.apache.commons.lang3.StringUtils;

public class Main {
    public static void main(String[] args) {
        String string = "";
        System.out.println(StringUtils.defaultIfBlank(string, "String1"));
        string = "    ";
        System.out.println(StringUtils.defaultIfBlank(string, "String2"));
    }
}

Output:-

String1
String2

The first string literal is an empty string and the latter contains only whitespaces. Since they contain only whitespaces or the empty string therefore the StringUtils defaultIfBlank() Method returns the second argument passed within it.

import org.apache.commons.lang3.StringUtils;

public class Main {
    public static void main(String[] args) {
        String string = "Human";
        System.out.println(StringUtils.defaultIfBlank(string, "String1"));
    }
}

Output:-

Human

In this case, the string contains a valid length of string excluding the whitespaces. Therefore StringUtils defaultIfBlank() Method returns the string itself.

import org.apache.commons.lang3.StringUtils;

public class Main {
    public static void main(String[] args) {
        String string = null;
        System.out.println(StringUtils.defaultIfBlank(string, "String1"));
        string = "null";
        System.out.println(StringUtils.defaultIfBlank(string, "String2"));
    }
}

Output:-

String1
null

Initially, the string contains a null reference, therefore, StringUtils defaultIfBlank() Method returns the second argument. Later we assigned “null” literal to the string which has a valid length without whitespaces therefore StringUtils.defaultIfBlank() Method returns string itself.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *