Java Reference
In-Depth Information
b= ( byte ) (b + 1);
Prefix operator ( byte ) is called a cast . It casts or converts the type of the expres-
sion to type byte . Similarly, we can use the casts ( short ), ( int ), and ( long ).
Widening casts —casts that convert from a narrower type to a wider type—
are unnecessary because Java promotes values to a wider type when needed.
Narrowing casts —casts that convert from a wider type to a narrower type—
must always be written explicitly because Java will never automatically convert
to a narrower type because it may lose information.
Identity casts , like ( int )5 , are also possible, but there is no need for them.
Casts have higher precedence than binary operators
A cast like ( byte ) has higher precedence than operators like addition and
multiplication. For example, consider this assignment:
b= ( byte ) b + 1; // illegal
The assignment is equivalent to:
b= (( byte ) b) + 1; // illegal
Thus, the addition is an int addition and produces an int result, which can-
not be assigned to a byte , so the assignment is syntactically illegal. The assign-
ment statement should be written this way:
b= ( byte ) (b + 1); // legal
6.4
Floating-point types double and float
6.4.1
Type double
The values of type double are numbers that can have a fractional part, like -
.000045 and 35.4 . You can view these as the so-called “real numbers”, but you
cannot represent all real numbers exactly. For example, the number 1/3 =
.333333… has an infinite number of 3 's in it, so, because a double value occu-
pies a finite amount of space (eight bytes), the number 1/3 cannot be repre-
sented exactly in type double . Similarly the square root of 2 and pi , the ratio of
the circumference of a circle to its diameter, cannot be represented exactly in
type double . Type double serves only as an approximation of the real numbers.
We give you enough information so that you can write programs that use
type double . However, to really use the type well, you need to know more than
we can explain in this topic. A later course, perhaps in numerical analysis, will
explain all the nuances of type double .
Lesson pages
6-3 and 6-4
discuss type
double.
Literals of type double
There are three forms of double literal:
Search WWH ::




Custom Search