Sunday, 9 October 2011

Divide by Zero in case of Java

One of the good interview questions I found was related to divide by zero.
Lets take the case:

What will be the output of this code snippet?

public class NaN {

public static void main(String[] args) {
double d = 2.0 / 0.0;
System.out.println(d);
}
}

What's the answer: The code will not compile or will it throw a DivideByZero error? Both are wrong. The code compiles fine and the output is,
Infinity

Let's check another code snippet,

public class NaN {

public static void main(String[] args) {
double d = 0.0 / 0.0;
System.out.println(d);
}
}

The output in this case is,
NaN

No comments:

Post a Comment