I have a string, which is read from a database. The string can be just “null”. I need to decide whether it is null or not? Among the following ones, what is the appropriate way to do it?
String a = …;
If (a == null)
If ( a.length == 0)
I also see something like
If a.equals(“ “)
How does this work?
if (a == null)In Java,
==compares references, so you can check to see whether the reference a refers to null.a.lengthanda.equalswould throw NullPointerExceptions ifaequaled null, since you can’t call methods on null.When you compare Strings with equals, that:
So even if we could call equals on null (which we can’t, as mentioned before), it’d never return true anyway, as according to the documentation.
String.length would return zero only if
aequaled"", an empty string. As according to the method:When in doubt, just test it out! 🙂