Reputation: 11558
I find it confusing to try to figure out when a value will be computed as a double and when it will be cast to an integer in Java. For example:
System.out.println( 1 / 3 );
System.out.println( 1 / 3d );
System.out.println( 1d / 3 );
System.out.println( 1/ 1d / 3 );
produces:
0
0.3333333333333333
0.3333333333333333
0.3333333333333333
Am I safe in assuming that if there is one double anywhere in the expression then the whole expression will be always be a double and only if each and every value is an integer will it be treated as integer division?
Upvotes: 0
Views: 79
Reputation: 2790
Yes you are right, if one of the operands is a double
then the other one will be promoted to double
as well - this includes all primitive types except boolean
.
A more detailed/verbose explanation can be found here: Java Language Specification
But you should be careful about the evaluation order of the expressions. 1 / 2d / 3
will give a different result than 1 / 2 / 3d
since these are in fact 2 expressions: (1 / 2d) / 3
. Also 1d + 2 / 3
will give a different result than 1 + 2 / 3d
since /
get evaluated before +
. So if you want your code to be correct, you have to make sure that the first expression already gets evaluated to double
.
Upvotes: 1
Reputation: 14425
To quote the spec:
4.2.4. Floating-Point Operations
If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).
15.17. Multiplicative Operators
The operators *, /, and % are called the multiplicative operators.
...
The type of a multiplicative expression is the promoted type of its operands.
If the promoted type is int or long, then integer arithmetic is performed.
If the promoted type is float or double, then floating-point arithmetic is performed.
So yes, you are safe in assuming that the resulting expression will always be double
if there is at least one double
involved.
Upvotes: 2
Reputation: 655
You are correct. Whenever there's more than one different data type within an arithmetic statement, Java implicitly converts all values to one unifying type so that all numbers have the same data type. In the case of the second and third values, Dividing an integer by a double leads to the integer being converted into a double, but within an integer-integer division, there's no need for Java to convert to a unifying type, and so the result remains as an integer.
The following link explains this in great detail: mathbits.com/MathBits/Java/DataBasics/Mathoperators.htm
Upvotes: 1