Java Reference
In-Depth Information
Converting a numeric value from a smaller numeric type to a larger type is easy: simply assign the smaller type to
the larger type. For example:
doubleTest = intTest;
This works for all the numeric types from smallest to largest. Assuming the following:
byte byteTest = 1;
short shortTest = 2;
int intTest = 3;
long longTest = 4;
float floatTest= 5;
double doubleTest = 6;
Running the following:
System.out.println(" " + byteTest + shortTest +
intTest + longTest + floatTest + doubleTest);
Would result in:
12345.06.0
If we then assigned the values as follows:
doubleTest=floatTest=longTest=intTest=shortTest=byteTest;
and displayed the values as follows:
System.out.println(" " + byteTest + shortTest + intTest +
longTest + floatTest + doubleTest);
the result would be:
11111.01.0
Notice that the assignments are made from right to left. In other words, the byte variable byteTest (with a value of 1)
was promoted to the larger type of short first and then assigned to shortTest, and then shortTest was converted to int
and assigned to intTest, and so on.
Going from a larger primitive variable to a smaller primitive type requires casting and is a little more
complicated. The syntax for casting is: the smaller primitive variable, the equal sign, the smaller variable type in
parentheses, then the larger primitive variable. For instance, assuming doubleTest equals 6.0, the following statement:
intTest = (int)doubleTest;
would set intTest to the value 6.
Casting is relatively simple until a value is too large for the smaller type. For instance, changing doubleTest's
value to 9876543210987.99 and then casting to each of the smaller types yields a variety of values. For instance, the
float variable value would be 9876543000000. Because float only supports 7 digits of precision, only the seven highest
digits (9876543) are saved and all finer precision is lost. (This float value would actually display in scientific notation.
Controlling the appearance of numbers is a whole other can of worms that we will cover later.)
 
Search WWH ::




Custom Search