An important thing to ask yourself: Are null
and empty logically equivalent for what you're doing?
If so, you might want to use this:
if (currentTimeslot == null || currentTimeslot.isEmpty()) {
// Do stuff
}
If the first half of that statement evaluates to true
, Java won't bother with the second half, thus protecting you from the null-pointer exception.
Another approach would be to normalize your data; if you want null
and an empty string to be treated as the same thing, just do something like this early in the code:
if (currentTimeslot == null) currentTimeslot = "";
Now you don't have to defensively null-check every time you use it.
As to why you're getting the exception: in Java, all objects (any variable that isn't a primitive type like int
, boolean
, etc.) is null
until you initialize* it. If you try to access any methods or fields of that object, you'll get a null-pointer exception because you're asking the code to access something that doesn't actually exist yet. In Java, you either want to make sure your objects get initialized to something early or do a lot of defensive null-checking (either with if (variable != null) { ... }
or try { ... } catch (NullPointerException npe) { ... }
blocks) to prevent exactly the problem you're running into.
*-- Initialize it with something other than null
, of course.