Java Reference
In-Depth Information
true
if (condition) {
false
} else {
}
FIGURE 2.6:
The
if-else
construct.
TABLE 2 . 2 :
Java comparison
operators.
Operator
Meaning Example
==
equal
3 == 3
>
=
greater or equal
3
>
=3
>
greater
4
>
3
<
smaller
3
<
5
<
=
smaller or equal
3
<
=3
! =
different
5! = 3
The operators = and == are very different. For example, the statement
i=3
assigns the value of 3 to the integer
i
. Conversely, the condition
(i == 3)
checks if
the value of
i
is equal to 3. Remember to never use a single equality inside a condition.
Inside a conditional statement, always use double equality.
The operator == returns
true
when the two operands are equal. Conversely, the oper-
ator != returns
true
when the two operands are distinct. For example, the last two lines of
our code can be rewritten as follows.
if
(z != x
∗
y)
{
System. out . println (
"You need more practice"
);
}
else
{
System. out . println (
"Congratulations!"
);
}
Note that it is not required that an
if
statement has an
else
part; see Figure 2.7. For
example, the last two lines of our program can be rewritten as follows.
if
(z == x
{
System. out . println (
"Congratulations!"
);
return
;
System. out . println (
"You need more practice"
);
The statement
return
simply terminates the method. A return statement inside the
main
method terminates the program. Therefore, the last line of code in the above code
snippet will only be executed when
z
is different from
x
y)
∗
y
.The
if-else
construct may
become dicult to understand when there are multiple
if
and
if-else
statements nested
∗