5

I am working in a Java project and my code shows weird behavior. Here is my code:

String access = String.valueOf(getStringvalue());
Boolean isBlank = StringUtils.isBlank(access);

In the above code, 'access' object can have null values. And it is said that if we pass a null value to StringUtils.isBlank(), it will return true. But here I returned only false value when access is null. What is the reason for this behavior?

2
  • check the implementation of StringUtils class. It is from apache common utils? Commented Nov 24, 2015 at 7:47
  • 5
    If you pass null to String.valueOf you get the string "null". That is not null and it is not blank. Commented Nov 24, 2015 at 7:47

2 Answers 2

5

I also had this problem and found the trick just after saw the source code of String.valueof(). The source code of String.valueof() is below.

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Therefore when you pass a null object, you will get a 'null' String. Therefore your StringUtils.isBlank() will treat is as a String rather than a null object and you will get a 'false' booean value.

Hope it helps.!

Sign up to request clarification or add additional context in comments.

4 Comments

No need to look at the source code - this is the documented behaviour of String.valueOf. It's not clear why the OP is calling String.valueOf at all...
"null" is a string with 4 characters: n, u, l and l. It's a string, like any other string.
@JBNizet Nice explanation. So valueOf(null) will return "null" as string ?
Yes, as documented. docs.oracle.com/javase/7/docs/api/java/lang/…: Returns: if the argument is null, then a string equal to "null"
0

I tested those code and they give the same result.

 Boolean isBlank = StringUtils.isBlank("");
 System.out.println(isBlank);// give true

and

 Boolean isBlank = StringUtils.isBlank(null);
 System.out.println(isBlank);// give true

2 Comments

String s1; is not always the same as String s1 = null; Just try and create a String as a local variable, it doesn't get a default value.
println(true) and println("true") will print the same thing, though they are different types. If you pass the same two values to StringUtils.isBlank(), they will give a different outcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.