Java Reference
In-Depth Information
9.4. Type Conversions
The Java programming language is a strongly typed language, which
means that it checks for type compatibility at compile time in almost all
cases. Incompatible assignments are prevented by forbidding anything
questionable. It also provides cast operations for times when the compat-
ibility of a type can be determined only at run time, or when you want to
explicitly force a type conversion for primitive types that would otherwise
lose range, such as assigning a double to a float . You learned about type
compatibility and conversion for reference types on page 90 . In this sec-
tion you will learn about conversions as a whole, for both primitive and
reference types, and the contexts in which those conversions are auto-
matically applied.
9.4.1. Implicit Type Conversions
Some kinds of conversions happen automatically, without any work on
your partthese are implicit conversions.
Any numeric value can be assigned to any numeric variable whose type
supports a larger range of valuesa widening primitive conversion. A char
can be used wherever an int is valid. A floating-point value can be as-
signed to any floating-point variable of equal or greater precision.
You can also use implicit widening conversion of integer types to floating-
point, but not vice versa. There is no loss of range going from integer to
floating point, because the range of any floating-point type is larger than
the range of any integer.
Preserving magnitude is not the same as preserving the precision of a
value. You can lose precision in some implicit conversions. Consider, for
example, assigning a long to a float . The float has 32 bits of data and
the long has 64 bits of data. A float stores fewer significant digits than a
long , even though a float stores numbers of a larger range. You can lose
data in an assignment of a long to a float . Consider the following:
 
Search WWH ::




Custom Search