Java Reference
In-Depth Information
Now we evaluate the additive operators from left to right:
26 + 3 - 4
29
- 4
25
Mixing Types and Casting
You'll often find yourself mixing values of different types and wanting to convert
from one type to another. Java has simple rules to avoid confusion and provides a
mechanism for requesting that a value be converted from one type to another.
Two types that are frequently mixed are int s and double s. You might, for exam-
ple, ask Java to compute 2 * 3.6 . This expression includes the int literal 2 and the
double literal 3.6 . In this case, Java converts the int into a double and performs
the computation entirely with double values; this is always the rule when Java
encounters an int where it was expecting a double .
This becomes particularly important when you form expressions that involve
division. If the two operands are both of type int , Java will use integer (truncating)
division. If either of the two operands is of type double , however, it will do real-
valued (normal) division. For example, 23 / 4 evaluates to 5 , but all of the follow-
ing evaluate to 5.75 :
23.0 / 4
23. / 4
23 / 4.0
23 / 4.
23. / 4.
23.0 / 4.0
Sometimes you want Java to go the other way, converting a double into an int .
You can ask Java for this conversion with a cast. Think of it as “casting a value in a
different light.” You request a cast by putting the name of the type you want to cast to
in parentheses in front of the value you want to cast. For example,
(int) 4.75
will produce the int value 4 . When you cast a double value to an int , it simply
truncates anything after the decimal point.
If you want to cast the result of an expression, you have to be careful to use paren-
theses. For example, suppose that you have some books that are each 0.15 feet wide
and you want to know how many of them will fit in a bookshelf that is 2.5 feet wide.
You could do a straight division of 2.5 / 0.15 , but that evaluates to a double result
that is between 16 and 17. Americans use the phrase “16 and change” as a way to
express the idea that a value is larger than 16 but not as big as 17. In this case, we
 
Search WWH ::




Custom Search