To test for actual nullity, use ==
like this:
if (site == null)
Or indeed the conditional operator, for situations like the one shown:
System.out.println(site == null ? "null" : "notnull");
Note that a null reference is not the same as an empty string. How do you want an empty string to behave? If you truly had a null reference, then your current code would have thrown a NullPointerException
.
The simplest way for testing an empty string is with the isEmpty
method:
System.out.println(site.isEmpty() ? "empty" : "not empty");
Note:
- This will throw an exception if
site
really is null
- This will treat whitespace as irrelevant
If you want to test for null/empty/empty-or-whitespace there are various third-party libraries which have that functionality.