lingui.st Translating software made easy

Math is logical – not in Java

Posted on April 2, 2008

A few weeks ago a teammate pointed out some weird behavior of Java in handling NaN values and doing calculations. So, I further investigated the issue and here is the result. It’s funny and sad at the same time …
[sourcecode language='java']// lets play with primitives and their corresponding classes
Double d = Double.valueOf(Double.NaN);
// expected result NaN
System.out.println(”d=” + d);
// the primitive value is still Not a Number
System.out.println(”d.doubleValue()=” + d.doubleValue());
// again 10 + Not a Number is still not a number
System.out.println(”d.doubleValue()+10=” + (d.doubleValue() + 10));
// aha the long value of Not a Number is a number! It is zero.
System.out.println(”d.longValue()=” + d.longValue());
// the same with an int value
System.out.println(”d.intValue()=” + d.intValue());
// since it is a number we can add, multiply, and divide it
System.out.println(”(d.longValue()+1000)*2/4=”+ ((d.longValue() + 1000) * 2 / 4));
// nice, it is possible to cast Not a Number to a Number!
System.out.println(”(int)d.doubleValue=” + ((int) d.doubleValue()));
// ok, now you say everything is fine when you are using primitives
// alone. let’s try this
// dividing an int with zero causes an ArithmeticException. what we expected
try {
System.out.println(1 / 0);
} catch (ArithmeticException e) {
System.out.println(”(1/0) throws an ArithmeticException.”);
}
// same with a long
try {
System.out.println(”1l / 0=” + 1l / 0);
} catch (ArithmeticException e) {
System.out.println(”(1l/0) throws an ArithmeticException.”);
}
// you expect the same behavior with a double, but now it is Infinity
System.out.println(”1. / 0=” + 1. / 0);
// Same with float
System.out.println(”1.f / 0=” + 1.f / 0);
// I don’t say the result of this one. a hint: back to the roots :)
System.out.println(”1. / 0 * 0=” + 1. / 0 * 0);[/sourcecode]

Related posts:

  1. hello blog
  2. Sun (Oracle) going to launch a Java App Store!
  3. Unlimited hotness from Linz for the Java Virtual Machine & JRuby

Tags: