How can I check whether a string is not null and not empty?
public void doStuff(String str)
{
if (str != null && str != \"**here I want to check
test equals with an empty string and null in the same conditional:
if(!"".equals(str) && str != null) {
// do stuff.
}
Does not throws NullPointerException
if str is null, since Object.equals() returns false if arg is null
.
the other construct str.equals("")
would throw the dreaded NullPointerException
. Some might consider bad form using a String literal as the object upon wich equals()
is called but it does the job.
Also check this answer: https://stackoverflow.com/a/531825/1532705