No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Answer from Jon Skeet on Stack OverflowNo, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Use StringUtils.isEmpty instead, it will also check for null.
Examples are:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
See more on official Documentation on String Utils.
Why does the order of String == null || String.isEmpty() matter? Or does it?
What is the correct way to check if a String is empty or null in Java, and how can I avoid potential errors? - TestMu AI Community
If a string is null, doesn't isEmpty() throw a Nullpointerexception when used?
Shorter (efficient) way to check if a string is null or empty?
Videos
I just completed MOOC, Java part II, exercise 19 for week 9 and found that the order I placed name.isEmpty() or name == null was the key to get it's tests to pass.
The test which failed was one that tested a null but I don't understand why it matters since it's an or statement.
Thank You
So this fails
public Person(String name, int age) {
if ( name.isEmpty() || name == null || name.length() > 40) {
throw new IllegalArgumentException("Name is an invalid length.");
} else {
this.name = name;
}
if ((age < 0) || (age > 120)) {
throw new IllegalArgumentException("Age is not a valid range");
} else {
this.age = age;
}
}But this passes
public Person(String name, int age) {
if ( name == null || name.isEmpty() || name.length() > 40) {
throw new IllegalArgumentException("Name is an invalid length.");
} else {
this.name = name;
}
if ((age < 0) || (age > 120)) {
throw new IllegalArgumentException("Age is not a valid range");
} else {
this.age = age;
}
}