Azimuth Azimuth - 4 months ago 22
Java Question

&& (AND) and || (OR) in IF statements

My question might be very basic but still I think it worths to ask. I have the following code:

if(!partialHits.get(req_nr).containsKey(z) || partialHits.get(req_nr).get(z) < tmpmap.get(z)){
partialHits.get(z).put(z, tmpmap.get(z));
}


where
partialHits
is a HashMap. What will happen if the first statement is true? Will Java still check the second statement? Because in order the first statement to be true, the HashMap should not contain the given key, so if the second statement is checked, I will get
NullPointerException
.

So in simple words, if we have the following code

if(a && b)
if(a || b)


would Java check
b
if
a
is false in the first case and if
a
is true in the second case?

Answer

No it will not be evaluated. And this is very useful. Like you need to test, if a String is not null or empty, you can write:

if (str != null && !str.isEmpty()) {
  doSomethingWith(str.charAt(0));
}

or, the other way round

if (str == null || str.isEmpty()) {
  complainAboutUnusableString();
} else {
  doSomethingWith(str.charAt(0));
}

If we hadn't 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.

Comments