Java Reference
In-Depth Information
You cannot write an
if
statement like this:
if (i = 5) /* A compile-time error */
statement
This
if
statement will not compile because
i = 5
is an assignment expression and it evaluates to an
int
value
5. The condition expression must return a
Boolean
value:
true
or
false
. Therefore, an assignment expression cannot
be used as a condition expression in an
if
statement, except when you are assigning a
Boolean
value to a
boolean
variable, like so:
boolean b;
if (b = true) /* Always returns true */
statement
Here, the assignment expression
b = true
always returns
true
after assigning
true
to b. In this case, the use of
the assignment expression in
if
statement is allowed because the data type of expression
b = true
is
boolean
.
You can use the ternary operator in place of simple
if-else
statement. Suppose, if a person is male, you want to
set the title to “Mr.” and if not, to “Ms.”. You can accomplish this using an
if-else
statement and also using a ternary
operator, like so:
String title = "";
boolean isMale = true;
// Using an if-else statement
if (isMale)
title = "Mr.";
else
title = "Ms.";
// Using a ternary operator
title = (isMale ? "Mr." : "Ms.");
You can see the difference in using the
if-else
statement and the ternary operator. The code is compact using
the ternary operator. However, you cannot use a ternary operator to replace all
if-else
statements. You can use the
ternary operator in place of the
if-else
statement only when the
if
and
else
parts in the
if-else
statement contain
only one statement and both statements return the same type of values. Because the ternary operator is an operator, it
can be used in expressions. Suppose you want to assign the minimum of
i
and
j
to
k
. You can do this in the following
declaration statement of the variable
k
:
int i = 10;
int j = 20;
int k = (i < j ? i : j); // Using a ternary operator in initialization
The same can be achieved using an
if-else
statement, as shown:
int i = 10;
int j = 20;
int k;
if (i < j)
k = i;
else
k = j;