Java Reference
In-Depth Information
6.
On your own, try modifying the program so that it uses and displays 1's and 0's,
rather than true and false. This may involve a bit more effort than you might at first
think!
Expressions
Operators, variables, and literals are constituents of
expressions
. You probably already
know the general form of an expression from your other programming experience, or from
algebra. However, a few aspects of expressions will be discussed now.
Type Conversion in Expressions
Within an expression, it is possible to mix two or more different types of data as long as
they are compatible with each other. For example, you can mix
short
and
long
within an
expression because they are both numeric types. When different types of data are mixed
within an expression, they are all converted to the same type. This is accomplished through
the use of Java's
type promotion rules
.
First, all
char
,
byte
, and
short
values are promoted to
int
. Then, if one operand is a
long
,
the whole expression is promoted to
long
. If one operand is a
float
operand, the entire ex-
pression is promoted to
float
. If any of the operands is
double
, the result is
double
.
It is important to understand that type promotions apply only to the values operated upon
when an expression is evaluated. For example, if the value of a
byte
variable is promoted
to
int
inside an expression, outside the expression, the variable is still a
byte
. Type promo-
tion only affects the evaluation of an expression.
Type promotion can, however, lead to somewhat unexpected results. For example, when
an arithmetic operation involves two
byte
values, the following sequence occurs: First, the
byte
operands are promoted to
int
. Then the operation takes place, yielding an
int
result.
Thus, the outcome of an operation involving two
byte
values will be an
int
. This is not
what you might intuitively expect. Consider the following program: