Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between null and StringUtils.isBlank()

Tags:

java

null

I want to check if a String is empty or not and I would like to know the differences between the following and which one is better and on which occasions.

Specially because I'm getting this error if I use "isNotBlank": "cannot be cast to java.lang.String".

this.text.getData() != null <--- works perfectly fine.
StringUtils.isNotBlank((String)this.text.getData()) <- doesn't work.

If "null" is not the best solution, what could I use?

like image 994
this.user3272243 Avatar asked Aug 31 '26 17:08

this.user3272243


2 Answers

If you expect any data that is not null to be a String then this.text.getData() != null might work but your code will later on have a class cast problem and the fact that the cast to String is not working shows a deeper problem.

If it is OK for 'data' to be some object of some type, then StringUtils is simply not the right solution and the Null-check is the right thing to do!

like image 107
André R. Avatar answered Sep 03 '26 07:09

André R.


isNotBlank() Checks if a String is not empty (""), not null and not whitespace only.

public static boolean isNotBlank(String str)
Checks if a String is not empty (""), not null and not whitespace only.

See Doc isNotBlank

!= null check only if the object is null

I'm getting this error if I use "isNotBlank" "cannot be cast to java.lang.String".

That's because may be your getData() return something other than String and that can't be casted to String.

And you need to know you can do != null with any type of object but to do isNotBlank() it should be a String.

like image 28
Saif Avatar answered Sep 03 '26 08:09

Saif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!