Java, logical operators and denial: && (AND), || (OR) and! (negation)


Completing our knowledge about Boolean algebra, we'll explain a little about AND and OR logical operators.

But do not be scared by the word 'algebra', if you know English and have common sense, you'll understand what will be explained.


Logical operators AND (&&) and OR (||)

Often, we want to test if certain conditions are true.
Generally, we want to test more than one condition.

For example:
"For you be approved in college, you need to get an average greater than 6.0 in all subjects AND average more than 7 in, at least, 3."

Noticed ? It means that the two conditions have to be satisfied.

Now the same example, using the OR.

"For you be approved in college, you need to get an average greater than 6.0 in all subjects OR greater than 7 on average at least 3."

Now it's easier because, you only need to satisfy one of the conditions. You can get 7 in Mathematics, Physics and Chemistry and 0 all the others, because you don't need 6.0 on average in other, anymore.

But nothing prevents you from satisfying the two conditions.

Formalizing

'AND' and 'OR' are our analogies to human language.
The computer speaks the language of bits, and has a special language.

In Java, to represent the 'AND' and Java communicate with your machine, you will use the representation: &&

To represent the 'OR', use ||

Then, we formalize the examples. Conditions are:
condition_A = all averages higher than 6.0
condition_B = average greater than 7 in at least three materials

The first example is represented by: (condition_A && condition_B)
The second example is represented by: (condition_A || condition_B)


Denying statements: !

To deny a statement or condition, simply put a exclamation point (!) before such statement / condition.

For example, a good student (Java student) has his notes represented by: condition_A
But a bad student has his notes represented thus: !condition_A

!condition_A means that not all averages are greater than 6.0

What is the opposite of truth? False, of course.
In Java, the following forms are equal:
true =!false
false = !true

No comments: