You have probably guessed from earlier discussions that 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 will be converted to type `int` where necessary and use 32-bit arithmetic to produce the result, as we saw earlier in the chapter.

It may well be that the default treatment of mixed expressions listed in the preceding section is not what you want. For example, suppose you have defined a `double` variable `result`; and two variables, `three` and `two`, of type `int` with the values 3 and 2, respectively. If you compute the value of `result` 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 ...

Start Free Trial

No credit card required