Casting
Casting is used to convert data of one type to another. For example, you can use casting to convert a double
to an int
.
For more information on the int
or double
data types, see Integer Data Types and Floating-point Data Types.
When you use casting, you run the risk of losing information. A double
can hold larger numbers than an int
, for example. In addition, an int
can’t hold the fractional part of a double
. As a result, if you cast a double
to an int
, you run the risk of losing data or accuracy — so 3.1415
becomes 3
, for example.
Casting does not round numbers up. For example:
double price = 9.99;
int iPrice = (int) price;
Here, iPrice
is assigned the value 9
. If you want to round the double value when you convert it, use the round
method of the Math
class, as described within Math Class in Part 3.
To cast a value from one type to another, you use a cast operator, which is simply the name of a primitive type in parentheses placed before the value you want to cast. For example:
double pi = 3.1314;
int iPi;
iPi = (int) pi;
For more information about rounding, see Math Class in Part 3.