This content has been marked as final. Show 10 replies
perfectplanet.co.uk wrote:sizeBytes is an int. When you perform sizeBytes * 8, the result is greater than Integer.MAX_VALUE and so it overflows into the negative domain of int.
double downloadTime4 = ( sizeBytes * 8) / (1048576 * downlinkRate);
By casting to a double you're telling it to perform a multiplication with double operands and a double result, and as a result you get back the correct sign.
perfectplanet.co.uk wrote:They're only errors from your point of view. Should Java check every mathematical operation you do to safe guard from overflow? Some would argue yes. I personally like the fact that Integer.MAX_VALUE + 1 == Integer.MIN_VALUE. It might make more sense to you if you understood how two's-complement number representation works.
Surely Java doesn't just ignore these errors?
Say we had a 3-bit integer type. This is how the numbers are represented:
If you look at it closely, you can see how simple this makes certain arithmetic operations. Take adding by 1. No matter what happens, the next number can be represented by adding a 1-bit to the lowest significant bit. When you add 1 to 011 (3), what's the result? 100 (-4). When you add 1 to 111 (-1), what happens? You get 1000, which in 3 bits is 000 (0), which makes sense as -1 + 1 = 0.
3 = 011 2 = 010 1 = 001 0 = 000 -1 = 111 -2 = 110 -3 = 101 -4 = 100
So it helps to have an idea of binary representations of numbers.
perfectplanet.co.uk wrote:So you saw that Java raises no exception and then asked "Surely Java doesn't just ignore these errors?" Websters defines "ignore" as
Of course I ran it, how do you think I came up with the values?
Java raises no exception in the calculation.
1. To be ignorant of or not acquainted with. [Archaic]
Philosophy would solidly be established, if men would more carefully distinguish those things that they know from those that they ignore. Boyle.
2. (Law) To throw out or reject as false or ungrounded; -- said of a bill rejected by a grand jury for want of evidence. See Ignoramus.
3. Hence: To refuse to take notice of; to shut the eyes to; not to recognize; to disregard willfully and causelessly; as, to ignore certain facts; to ignore the presence of an objectionable person.
Interesting! Thanks for the explanation. I certainly wouldn't expect C/C++ to do this kind of checking, but I would have expected Java to (not because I necessarily want it to, but it seems like the kind of safe thing Java would do)
Thanks for the replies chaps - I'll be looking out for this in future.
PS - just to make clear, my heartfelt thanks are directed at endasil and sabre... and my demonstration of the meaning of the word 'ignore' is firmly directed at the other.
Beats me why some people find it necessary to be sarcastic in a programming forum... they obviously don't have enough work to do!