Java Reference
In-Depth Information
TABLE 2 . 3 :
Java operators on Boolean values.
Operator Meaning Example
&&
and
T&&T=T T&&F=F F&&F=F
||
or
T
||
F=T T
||
T=T F
||
F=F
!
negation !T=F, !F=T
, is enclosed in single quotes. Conversely, a
string value, such as
"cat"
, is enclosed in double quotes. The above implementation is not
optimal. The second
if
statement can be misleading. A user may interpret it that
grade=
Note that a character literal, such as
'
A
'
'
when
x<
= 100. However,
x
must be also greater or equal to 90. Nested
if
statements can
quickly get confusing to interpret. Therefore, a good programming practice is to never have
too many nested
if
statements and avoid them if at all possible. A better implementation
is to combine the two
if
statements into a single
if
statement. Here is how this can be
done.
if
(x
'
A
>
=90&&x
<
= 100)
{
grade =
'A'
;
}
The “&&” operator is an operator that works on
boolean
values (i.e.,
true
/
false
values). It is the logical “and”. For example, the “+” operator can be used to add two
integers and return an integer. Conversely, the “&&” operator takes as input two
boolean
values and produces a
boolean
value. Java supports three operators on Boolean values; see
Table 2.3.
For example, if we want to give a letter grade of
(i.e., other) when the numeric
grade is smaller than 0 or bigger than 100, we can write the following code.
'O'
if
(x
>
100
||
x
<
0)
{
grade =
'O'
;
}
The operator “——” is the logical or operator. Note that the condition
(x>100 && x<0)
is not meaningful because
x
cannot be bigger than 100 and smaller than 0 at the same time.
The next statement is a rewrite of the last code snippet that uses the negation operator.
if
!(x
<
= 100 && x
>
=0)
{
grade =
'O'
;
}
We will go inside the
if
statement when it is not true that
x
is between 0 and 100. Note
that the following code snippet will not compile.
if
!(0
<
=x
<
= 100)
{
grade =
'O'
;
}
Thereasonisthat0
<
=
x
<
= 100 is not a valid condition. This is a statement that can
be written in math, but it is not recognized by the Java compiler. One rule to remember
is that the condition of an
if
statement must always be surrounded by parentheses. For
example, the following code snippet will produce a syntax error.
if
x
<
60
{
grade =
'F'
;
}
Our complete program is shown next.