There are just two values of type boolean: true and false. They are used as the values of expressions that have yes-or-no answers.
The following table shows some operators that yield boolean results and some operations on boolean values.
x == y
True if x and y are the same value. |
x != y
True if x and y are not the same value. |
x > y
True if x is greater than y. |
x < y
True if x is less than y. |
x >= y
True if x is greater than or equal to y. |
x <= y
True if x is less than or equal to y. |
!x
This is true if x is false, and false if x is true. |
x && y
This is true if both x and y are true, and false if either
of them is false.
If x is false, then y is not evaluated at all. For example, expression 3 > 4 && Math.max(z,w) == wdoes not compute Math.max(z,w) or ask whether its result is equal to w. |
x || y
This is true if either x is true or y is true or both are true. If x is true, then y is not evaluated. |
Be careful when translating from English to Java. English allows you to take liberties that Java does not. Common mathematical notation also allows you to write things that Java does not allow.
x < y < z
You cannot write combinations of comparisons this way. Write x < y && y < z. |
x is 1 or 2
Do not try to write this as x == 1 || 2. That treats 2 as a boolean value (which is considered true). To ask if x is 1 or 2, say x ==1 || x == 2. |
x is even
In English, is sometimes means "is equal to", and sometimes means "has the property". For example, "Jumbo is an elephant" does not indicate that "Jumbo" and "an elephant" are the same thing, but that Jumbo has the property of being an elephant. Do not try to use == with the property meaning, and write x == even. To test if x is even, write x % 2 == 0. If you have a method isPrime(x) that returns true if x is prime, do not write x == isPrime. Write isPrime(x). |
Some students get the idea that a boolean expression can only occur in a test, such as in an if-statement. But that is not true. Instead of
if(x > 0) { return true; } else { return false; }why not just write
return x > 0;which has the same effect.
See the coding standards for standards that you must follow in this course for writing boolean expressions.
What is the value of expression 4 > 3? Answer
What is the value of expression 6 >= 9? Answer
What is the value of expression 3 > 4 || 6 >= 9? Answer
What is the value of expression 2 == 2 && 5 >= 3? Answer
What is the value of expression !(3 == 3)? Answer
Give an expression that is equivalent to !(x == y), but that does not use the negation operator, !. Answer
Give an expression that is equivalent to !(x > y), but that does not use the negation operator, !. Answer
Give an expression that is true if x, y and z are all equal to one another. Answer