Does logical or ignores second statement if first is true

Sharon Dorot picture Sharon Dorot · May 9, 2014 · Viewed 13.6k times · Source

In Java (Eclipse), when having a statement such as if (true || false), it will end up true but the question is will the compiler evaluate the second statement if the first is true? This is of an importance to me because I have an operation I need to do if the variable is null OR it has a certain value. My statement looks like if (array == null || array[i] < array[j]). You can see the reason for my question, because if array is set to null then the second statement will produce an error. So, will the true from array == null suffice or will the compiler evaluate array[i] < array[j]) also?

Answer

Mena picture Mena · May 9, 2014

No it won't.

  • With boolean operator ||, if first term is true second term won't be evaluated.
  • With bitwise operator | both terms are evaluated

Similarly...

  • With boolean operator &&, if first term is false second term won't be evaluated
  • With bitwise operator &, both terms are evaluated

Java operators docs here.