Thursday, September 27, 2007

Interesting facts about JAVA

1. Divide by ZERO:

Java behaves differently when you divide real numbers (float/double) by zero. It will not going to throw any exception and the execution will resume from the next line itself.

But for the integer types (int/long), when you divide it by zero you will get Runtime exception more specifically it will give you ArithmeticException.

Example:

float f1 = 123.123f;

System.out.println("f1 / 0::" + f1 / 0);

System.out.println("-123.123 / 0::" + -123.123 / 0);

System.out.println("f1 % 0::" + f1 % 0);

Output:

f1 / 0::Infinity

-123.123 / 0::-Infinity

f1 % 0::NaN

2. Real number Multiplication:

There is one more strange behavior.

(Courtesy PK)

Can you guess the output of following statements:

System.out.println(8.995*100.0);

Or

System.out.println(9.995*100.0);

Output will be 899.4999999999999 and 999.4999999999999 resp.

But for all other similar types of multiplication it gives the output as *99.5 where * can be any number other than 8 and 9.