This week's book giveaways are in the Java EE and JavaScript forums. We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line! See this thread and this one for details.

Why these two statements give different result? System.out.println(4.3 - 2.3); 2.0 System.out.println(4.3f - 2.3f); 2.0000002 I mean why there is .0000002 Can anyone explain? Thank You Rishi

Well they are not the same expressions. 4.3 - 2.3 is promoted to double and so is calculated as 4.3d - 2.3d float and double arithmetic is full of tiny inaccuracies due to the way the numbers are stored internally and limiting precision.

Just to precise what Colin just said, 4.3 - 2.3 is not promoted to double since the expression already is of type double. If one specifies a floating point number without appending "f" directly after that number then the type defaults to double. So 4.3 (as well as 4.3d) is of type double and 4.3f is of type float. ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform

Originally posted by Colin Kenworthy: Well they are not the same expressions. 4.3 - 2.3 is promoted to double and so is calculated as 4.3d - 2.3d float and double arithmetic is full of tiny inaccuracies due to the way the numbers are stored internally and limiting precision.

Thanks for the answer, I have checked double always give precise answer but if you have substraction with float it does not. The inaccuracies are only in float, I think. Any comment? Rishi

Yes, beware. Double is more precise than float. But it is subject to the same type of imprecisions that you have seen using floats! The imprecisions are just smaller in magnitude. In particular, there is no guarantee that a given integer number can be represented precisely using a float or double. - Peter