Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java implicit casts that can lead to precision or magnitude loss? [duplicate]

I recently learned, while converting some Java code to C#, that Java's increment operator '+=' implicitly casts to the type of LHS:

int i = 5;
long lng = 0xffffffffffffL;  //larger than Int.MAX_VALUE
i += lng;                    //allowed by Java (i==4), rejected by C#

is equivalent to: (details here)

int i = 0;
long lng = 0xffffffffffffL;
i = (int)(i + lng);

thus silently causing the opportunity for loss of magnitude.

C# is more conscientious about this at compile-time:
Cannot convert source type long to target type int.

Are there other similar situations allowed by Java?

like image 658
Cristian Diaconescu Avatar asked Dec 19 '12 10:12

Cristian Diaconescu


1 Answers

A long can be promoted to a float or double, which results in a loss of accuracy:

public static void main(String[] args) {
    float f = Long.MAX_VALUE;
    double d = Long.MAX_VALUE;

    System.out.println(Long.MAX_VALUE);
    System.out.println(f);
    System.out.println(d);

}

prints

9223372036854775807
9.223372E18
9.223372036854776E18

I suspect C# does this the same way, though.

Aside from the compound assignment operators you already mentioned, I believe those to be all cases where an implicit conversion can change the value.

like image 151
meriton Avatar answered Oct 21 '22 13:10

meriton