Java Reference
In-Depth Information
Java calls this kind of variable a
boolean
,
5
and it can be assigned
true
or
false
,
or you can give it math expressions using any of these operators, all of which
return either
true
or
false
:
Equal to
(two equals signs)
==
!=
Not equal to
!
Not
(so “not true” is false, and “not false” is true)
<
Less than
>
Greater than
Less than or equal to
<=
>=
Greater than or equal to
&&
And
(true if both things are true)
||
Or
(true if either thing is true)
For example, given these variables
int
a = 10;
int
b = 5;
String
h =
new String
(
"Hello"
);
boolean
result = true;
boolean
badone = false;
Java will figure out these comparisons:
•
a==10
is
true
•
b==6
is
false
•
a<20
is
true
•
b>=5
is
true
•
a>100
is
false
•
result
is
true
•
!result
is
false
(pronounced “not result”—“not” returns the opposite of a value)
•
result&&badone
is
false
(pronounced “and”—true only if both are true)
•
result||badone
is
true
(pronounced “or”—true if either is true)
But this next one won't do what you think it should; it will not be
true
:
h ==
"Hello"
;
// Gotcha!
That one is tricky. For strings and objects (more on that in the next chapter),
use the
equals
function instead of the double equals sign (
==
), like this:
h.equals(
"Hello"
);
// is true
5.
Named for George Boole, the British mathematician, who came up with these ideas in
the 1800's.