Does logical or ignores second statement if first is true [duplicate]
Asked Answered
W

1

12

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?

Whin answered 9/5, 2014 at 10:12 Comment(0)
E
31

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.

Evaporite answered 9/5, 2014 at 10:13 Comment(3)
Thank you! I could have tested it on my expression but reaching the point where I could debug it is far away and it would be a shame to do all that work and end up fixing it.Whin
@SharonJDDorot - have a look at the Groovy Console (groovyconsole.appspot.com) - really useful for putting these little snippets in.Superman
flawless answer @EvaporitePernambuco

© 2022 - 2024 — McMap. All rights reserved.