Mixed Arithmetic Expressions
You can mix values of the basic types together in a single expression. The way mixed expressions are treated is governed by some simple rules that apply to each operator in such an expression. The rules, in the sequence in which they are checked, are:

If either operand is of type double, the other is converted to double before the operation is carried out.

If either operand is of type float, the other is converted to float before the operation is carried out.

If either operand is of type long, the other is converted to long before the operation is carried out.

The first rule in the sequence that applies to a given operation is the one that is carried out. If neither operand is double, float, or long, they must be int, short, or byte, so they use 32-bit arithmetic as we saw earlier.

Explicit Casting
It may well be that the default treatment of mixed expressions listed above is not what you want. For example, if you have a double variable result, and you compute its value using two int variables three and two with the values 3 and 2 respectively, with the statement:

result = 1.5 + three/two;

the value stored will be 2.5, since three/two will be executed as an integer operation and will produce the result 1. You may have wanted the term three/two to produce the value 1.5 so the overall result would be 3.0. You could do this using an explicit cast:

result = 1.5 + (double)three/two;

This causes the value stored in three to be converted to double before the divide operation takes place. Then rule 1 applies for the divide operation, and the operand two is also converted to double before the divide is executed. Hence the value of result will be 3.0.

Important You can cast any of the basic types to any other, but you need to take care that you don't lose information when you do so. Obviously casting from a larger integer type to a smaller has the potential for losing information, as does casting any floating point value to an integer. Casting from double to float can also produce effective infinity when the original value is greater than the maximum value for a float.


Casting in Assignments
When the type of the result of an expression on the right of an assignment statement differs from the type of the variable on the left, an automatic cast will be applied as long as there is no possibility of losing information. If you think of the basic types that we have seen so far as being in the sequence:

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

then 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, from double to float or long, for example, then you must use an explicit cast.
_________________________
My New site OpenEyes