To understand the answer, remind yourself of the truth tables of AND
and OR
operations:
AND true | false
\--------+-------
true | true | false
------+-------+-------
false | false | false
OR true | false
\--------+-------
true | true | true
------+-------+-------
false | true | false
Note the second column for AND
and the first column for OR
: they have identical values. This is the key to understanding the reason why AND
ignores its second argument when the first evaluates to false
: that's when the second argument does not matter (the second column). The opposite is true for the OR
operator: now a false
in the first argument means that the second one does matter. However, a true
in the first argument (the first column) means that the second argument can be ignored.
I thought the purpose of the && and the || was to sort of a help speed things along.
That's a smaller part of their purpose. Much bigger one is protection of right side of an expression based on its left side. Consider a situation where you want to guard against empty and null
strings. If &&
and ||
didn't "short circuit" the evaluation, you would be forced to write code like this:
if (s == null) return false;
if (s.length() == 0) return false;
The reason you can write
if (s == null || s.length() == 0) return false;
is the short circuiting: there is a guarantee that s.length()
would not be invoked on a null
string.