Logical Operators

"A method of human thought that involves thinking in a linear, step-by-step manner about how a problem can be solved."

The following definition was taken from en.wiktionary.org/wiki/Logic. It is worthwhile considering this for a moment. Computers and logic walk hand in hand. In order to program you must be able to think in a linear, step-by-step manner otherwise the code will not perform the tasks you intended. If you can not work through a problem in a logical fashion then you will be unable to come to a adequate programatic solution.

In programming a lot of logic derives from true and false, boolean, expressions. For example the expression -

50 > 90

This expression is wrong. 50 is not bigger than 90 (unless you know something that I do not!). As such the expression will evaluate to false. This is an example of a simple conditional test. We can then do further tests on this expression in order to derive more complex logical statements.

name = "bob" AND age > 50

The above expression will only be true if our variables name and age contained values which were "Bob" and greater than 50. Or putting that in simple English, it will only be true if Bob is a old codger! We therefore have linked the two logical test together by the keyword AND. Below are all of the possibilities of the above expression -

name = "bob"
age > 50
name = bob AND age > 50
True True True
True False False
False True False
False False False

The above expression will only be true if both of its parts equate to true. The *AND operator allows to test if 2 expressions are true. The related links will talk about the other two operators OR and NOT.

*note - In Java and C++ the AND operator is written as &&. There is a short circuit version which is just a single ampersand (&) but that is beyond the scope of this course.