8. Multiple Tests – And, Or, and Not
In the same way that the calculations that you do with numbers often involves more than just two numbers and one operation, the condition that you want to test in your if statement may involve more than just a simple comparison of two values. Unlike combining number calculations together where we just apply more of the same type of operators together such as a + b + c combining comparisons together is a little more complicated. We don't just need to be able to compare three or more values together such as a == b == c. We also need to be able to test for one condition being met and a second condition also being met or possible we have two different conditions where we need to test if either one or the other is met.
A logical && operator only returns true if both of the conditions are true. This means that when the condition on the left is false then the condition on the right is not tested at all since that cannot affect the result.
A logical || operator returns true as long as one, the other, or both of the conditions are true. This means that if the condition on the left is true then the condition on the right is not tested.
The ! operator is usually used specifically with Boolean variables in order to test for the reverse condition of what the variable contains.
Should we need to change this order for any reason then we can add parentheses around those parts that we want to be done first. If you are in any doubt as to what order the various parts will be done in then you can add the parentheses anyway in order to make it clearer how calculation should be done. It doesn't matter if the order would have been the same. Unnecessary parentheses will not affect the calculation, but will make it easier to read.
This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.