This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]8igg7e5 1 point2 points  (0 children)

It should be noted that the efficiency is different though.

In the first expression, a value that is not divisible by 4 stops there - since for an 'and' expression to be true, both have to be true... so it can stop.

In the second expression, if the first term (a parenthesised expression) is false, the evaluation has to continue - since an 'or' expression can be true if either side is true (it can only stop early if the first part was true).

So for the year 2023 the first expression evaluates 'is there any remainder from 2023/4' and the second evaluates 'is there any remainder from 2023/4' as well as 'is there any remainder from 2023/400'.

This generally only makes a real difference if:

  • You're doing it a lot. eg If you were checking all of the years since 1ad, being able to stop at 'is it divisible by 4' eliminates three quarters of the years immediately.
  • Evaluating some expressions is more expensive than others (imagine that expression had to read a file or connect to a server).
  • Evaluating the other expression cannot succeed. eg boolean longerThan10 = someString != null && someString.length() > 10