Reputation: 605
Can someone please explain/link any documentation that can differentiate between
Possible Loss of Precision Error
and
Lossy Conversion.
I cannot understand which error will occur under what circumstance. Any explanation with examples is deeply appreciated
Upvotes: 0
Views: 431
Reputation: 140309
The difference is the end of the number which gets chopped off:
Lossy conversion returns least-significant bits. It is described in JLS Sec 5.1.3:
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.
It is something like converting an int to a byte: you simply get the 8 least-significant bits in this case:
System.out.println((byte) 258); // 2
Loss of precision returns most-significant bits. It is described in JLS Sec 5.1.2:
A widening primitive conversion from int to float, or from long to float, or from long to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value.
It is something like storing an int in a float which is too large to be represented accurately
int i = (1 << 24) + 1;
float f = i;
System.out.println((int) f == i); // false, because precision is lost.
Upvotes: 1
Reputation: 944
You get possible loss of precision error when you try to cast such as double to int. You are trying to convert one primitive to another primitive but there is no enough space and you can get loss of your some bytes.
double x = 10.5; // 8 bytes
int y = x; // 4 bytes ; raises compilation error
You should look for the primitives documentation
Upvotes: 0