Strange division operator in Groovy

I am new to Groovy.

why this raises an exception at runtime:

int[] a = [1,2,3,4,5] int lo=0 int hi=4 int x = a[(lo+hi)/2] assert x == 3 

while they are in order:

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

and

 int i = (lo+hi)/2 int x = a[i] 
+8
groovy
source share
1 answer

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

See for example this tutorial :

The division operators "/" and "/ =" produce a double result if either operand is a Float or Double and 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 by integral types by casting the result of division . For example:

 assert (int)(3/2) == 1I; 
+11
source share

All Articles