This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.

Can you please explain to me why does the above two statements output different results?
I think it's something to do with java's representation of floats, not sure though.

You get different results because doubles and floats are inherently imprecise. Floating point numbers on computers are approximations, and so you get the results that you did. You shouldn't use floating point numbers for applications where you need real accuracy, such as when dealing with real money. In such a case, you'd probably want to look at the BigDecimal class.

Deepak Borania wrote:I think it's something to do with java's representation of floats, not sure though.

It's because (as Henry said, like most languages) it is represented in binary. It is not possible to represent 0.1 precisely, so you get that sort of result. Try representing 1 / 3 precisely in decimal, and you will see the problem.

Computers can only count in binary. That means multiples of 2, but also multiples of 1/2: 1/4, 1/8, etc. 0.1, or 1/10, is represented as follows: 1/16 + 1/32 + 1/256 + 1/512 + 1/4096 + 1/8192 + ...
If you represent 1/2 as .1, 1/4 as .01 etc, you get the following binary representation: .0001100110011001100...
As you can see, this repeats, just like 1/3 does when represented in decimals: 0.33333333...
So you see, just as we humans just quit after a number of threes, processors quit after a while as well. That's where numbers are rounded, and you get these imperfections.

BigDecimal is designed to handle these imperfections, so if you are bothered by it use that class.