Friday, April 11, 2008

Java's arithmetic operators

Here's a weird little one that confused me at first:

 @Test
public void testWeirdArithmeticOperators() {
double a = 1.0 / + + + 2.0;
assertTrue(0.5 == a);
String s = + + + + 0 + "abc" + "def";
assertEquals("0abcdef", s);
}


After playing about for a bit, switching some +es to -es and vice versa, I realised that the effect is that each + or - symbol could be rewritten as follows:
+ -> (+1)*
- -> (-1)*

So that the expression "+ + + 2.0" becomes "(+1) * (+1) * (+1) * 2.0" = 2.0, and the expression "- + + 2.0" becomes "-1 * +1 * +1 * 2.0" = -2.0. Thus, the sign of the result is negative for an odd number of - symbols and positive for an even number.

Seems a little pointless, but I suppose the logical way to see it is:
- + - x = - (+ - x) = - (+ (-x)). It makes sense then that the parser would accept it, but in it that form it looks wrong to (my) human eye.

Also, in writing this post I noticed that JUnit's assertEquals doesn't really like doubles:
assertEquals(0.5, 0) passes, as does assertEquals(Double.valueOf(0.5), Double.valueOf(0.0)) and other combinations. That's why I needed to use assertTrue(...) and == above. Huh.

No comments:

Post a Comment