Sunday, 19 August 2007

Operators and Assignments (Part 12)

Explicit Casting
It might be that the default way of treating the expressions listed above is not what you want. For example, consider the following Code,

double result;
int two = 2, eleven = 11;
result = 5.5 + eleven/two;


the result variable has a value of 10.5 (because the as both eleven and two are ints, the result of the division is rounded to an int). However, if you wanted the term 11/2 to produce the value 5.5 so the overall result would be 11.0, then you can do this using an explicit cast as follows:

result = 5.5 + (double)eleven/two;

This causes the value stored in eleven to be converted to double before the divide operation takes place and the operand two is also converted to double before the divide is executed. Hence the value of result will be 11.0.

This can (and must or compiler will complain) also go the other way where a large datatype is “squeezed” into a smaller datatype. Consider the next example:

long bigValue = 99.98765L;
int squeezedValue = (int)(bigValue);


without the (int) typecast in the second line, the compiler will flag an error. Variables can automatically be promoted to a longer form though without the need of explicit casting.
Consider the sequence of basic types,

byte --> short --> int --> long --> float --> double

an automatic conversion will be made as long as it is upwards through the sequence, that is from left to right. If you want to go in the opposite direction then you must use an explicit cast. Make sure that you don’t lose information when you do so.

No comments: