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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With