M/F 2:30-3:20 |
CS 1130: Transition to OO Programming Spring 2016 |
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Main
About: Overview Announcements Staff Consultants Calendar Materials: Texts DrJava Terminology Lectures: In-Class Web-Based VideoNote Assessment: Grading Assignments Labs Resources: CMS Piazza (link) Piazza (about) Java API Style Guide Academic Integrity |
Casts & Mixing Primitive TypesConverting one type of data into another must follow the rules
of casting. If a conversion results in the loss of precision,
as in an To convert type
For example, to convert integer data to floating point:
Expressions can promote to a wider type without
an explicit cast:
int
i=1; However, you can not assign a value to a more narrow type without
an explicit cast:
So a data type with lower precision (fewer bits) can be converted to a type of higher precision without explicit casting. To convert a higher precision type to a lower precision, however, an explicit cast is required or the compiler will flag an error. Note that when you cast a value of a wider type down to a more
narrow type, such as an Primitive Type Conversion TableBelow is a table that indicates to which of the other primitive types you can cast a given primitive data type. The symbol C indicates that an explicit cast is required since the precision is decreasing. The symbol A indicates that the precision is increasing so an automatic cast occurs without the need for an explicit cast. N indicates that the conversion is not allowed.
The * asterisk indicates that the least significant digits
may be lost in the conversion even though the target type allows
for bigger numbers. For example, a large value in an Mixed Types in an Expression
If an expression holds a mix of types, the lower precision
or narrower value operand is converted to a higher precision
or wider type. This result then must be cast if it goes to a
lower precision type: The process of converting a value to a wider or higher precision
integer or floating point type is called "numeric promotion".
The Java VM specification states the following rules for promotion
in an expression of two operands, as in
|