3

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?

9
  • 2
    StringUtils is for working on Strings. Your getData() method does not return a String, so it's not applicable. Commented Jun 16, 2015 at 9:15
  • @RealSkeptic shouldn't that be an answer? Commented Jun 16, 2015 at 9:15
  • Your method getData() can be return null. Is your method StringUtils.isNotBlank() include checking null value? Commented Jun 16, 2015 at 9:17
  • 4
    @sharonbn There are people who would write this as an answer, but I think it's more of a tip as to how the question itself is based on wrong assumptions, so the OP can consider whether he wants to change or delete or clarify it. Commented Jun 16, 2015 at 9:18
  • 1
    @laune That is obvious, I am asking it to make OP check it himself, and see for himself that something like StringUtils.isNotBlank(getHorse()) doesn't make sense and we should try looking for solution like StringUtils.isNotBlank(getHorseName()). Commented Jun 16, 2015 at 9:31

2 Answers 2

4

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!

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

Comments

3

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.

Comments

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.