Alex Rivera | Logout

strange division operator in Groovy

Asked 2011-02-21T07:25:27.647
9

I am new to Groovy.

why this throws exception on runtime:

int[] a = [1,2,3,4,5]
int lo=0
int hi=4

int x = a[(lo+hi)/2]
assert x == 3

while these are ok:

int x = a[(int)(lo+hi)/2]

and

int i = (lo+hi)/2
int x = a[i]
Edit
Report

1 Answer

15

In groovy a division results in a BigDecimal if the operands are of type Integer, Long, BigInteger or BigDecimal:

See for instance this tutorial:

The division operators "/" and "/=" produce a Double result if either operand is either Float or Double and a BigDecimal result otherwise (both operands are any combination of Integer, Long, BigInteger, or BigDecimal).

[...]

For example

1/2 == new java.math.BigDecimal("0.5");

[...]

Integer division can be performed on the integral types by casting the result of the division. For example:

assert (int)(3/2) == 1I;
answered 2011-02-21T07:29:17.587

Your Answer