Java Reference
In-Depth Information
SR 2.27
What value is contained in the integer variable
result
after the
following sequence of statements is executed?
result = 27;
result = result + 3;
result = result / 7;
result = result * 2;
SR 2.28
What value is contained in the integer variable
result
after the
following sequence of statements is executed?
int
base;
int
result;
base = 5;
result = base + 3;
base = 7;
SR 2.29
What is an assignment operator?
SR 2.30
If an integer variable
weight
currently holds the value 100, what is its
value after the following statement is executed? Explain.
weight -= 17;
Because Java is a strongly typed language, each data value is associated with a
particular type. It is sometimes helpful or necessary to convert a data value of
one type to another type, but we must be careful that we don't lose important
information in the process. For example, suppose a
short
variable that holds the
number 1000 is converted to a
byte
value. Because a
byte
does not have enough
bits to represent the value 1000, some bits would be lost in the conversion, and
the number represented in the
byte
would not keep its original value.
A conversion between one primitive type and another falls into one of two
categories: widening conversions and narrowing conversions.
Widening conver-
sions
are the safest because they usually do not lose information. They are called
widening conversions because they go from one data type to another type that
uses an equal or greater amount of space to store the value. Figure 2.5 lists the
Java widening conversions.
For example, it is safe to convert from a
byte
to a
short
because a
byte
is stored
in 8 bits and a
short
is stored in 16 bits. There is no loss of information. All widening
conversions that go from an integer type to another integer type, or from a floating
point type to another floating point type, preserve the numeric value exactly.
Search WWH ::
Custom Search