Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Casts
-
If information loss is possible when converting from one data type to another,
you must use casts to explicitly state your intentions.
-
If you don't, in most cases, the compiler will warn you.
-
To cast, put the type to which you wish to cast in parenthesis before the
expression that is to be casted.
-
In other words, to cast a float to an int:
float floatNumber = 12.33F;
int intNumber = (int) floatNumber;
-
The resulting int will have a value of 12.
-
Always be aware of the possibility of data loss. Better yet, try
to stick with one variable where possible.
-
And, when accuracy is key or large numbers are in use, use the BigInteger
and BigDecimal classes.
Created by: Brandan
Jones January 4, 2002