I put this into java and I was given the result 2. Was wondering why it isn't an ArithmeticException, as shouldn't (int)(2/0.9) turn into 2/0. All help is appreciated.
-
30.9 is a float, so 2 is promoted (or interpreted as) a float, and then the division takes place. The *result* is cast to int. – zzxyz Nov 30 '17 at 00:54
-
Oh so the division occurs before the cast? – Matthew Fenel Nov 30 '17 at 00:55
-
2@MatthewFenel Of course. `(2/0.9)` is in parentheses no? – Andrew Li Nov 30 '17 at 00:56
-
Yes. The parenthesis around `2/0.9` even make that explicit. `2/(int)0.9` should give you the result you are....expecting? – zzxyz Nov 30 '17 at 00:56
-
1Oh ok thanks! This is just for computer science lol. – Matthew Fenel Nov 30 '17 at 00:57
-
1parenthesis are 'slight' older than computer science, have few hundred years and well understood sense – Jacek Cz Nov 30 '17 at 01:11
-
2@zzxyz actually `0.9` is a *double*, not a float. – Bohemian Nov 30 '17 at 02:44
-
@Bohemian ah sorry I was using float loosely as in 'floating point' which is probably not a smart thing to do in this situation. – zzxyz Nov 30 '17 at 04:46
1 Answers
Your code is
(int) (2 / 0.9)
So the int
-cast is only applied to the result after computing 2 / 0.9
. Now 2 / 0.9
divides an int
by a double
value. In such a case the int
will also be interpreted as double
(2.0
in this case). The result is thus like
2.0 / 0.9 = 2.22...
This process is known as numeric promotion (it uses widening primitive conversion here JLS§5.1.2). From JLS§5.6:
A numeric promotion is a process by which, given an arithmetic operator and its argument expressions, the arguments are converted to an inferred target type
T
.T
is chosen during promotion such that each argument expression can be converted toT
and the arithmetic operation is defined for values of typeT
.
After that you cast to int
which will round the value to the next lower integer, 2
in this case. Thus the result is 2
.
What you expected would be the result of an expression like
2 / (int) 0.9
// or more explicit:
2 / ((int) 0.9)
which first casts the 0.9
to an int
before dividing. In this case you would correctly get
2 / 0
yielding the expected ArithmeticException
.

- 25,064
- 8
- 58
- 82