1

I was just studying OCJP questions and I found this strange code:

public class abc {
    public static void main(String[] args) {


        System.out.println(0.0%0.0!=0.0/0.0);// it return true

        System.out.println(0.0%0.0==0.0/0.0);// it return false


    }

}

When I ran the code, I got:

true
false

How is the output false when we're comparing two things that look the same as each other? What does NaN mean?

Baby
  • 5,062
  • 3
  • 30
  • 52
user2595138
  • 53
  • 1
  • 9

1 Answers1

2

Both 0.0 / 0.0 and 0.0 % 0.0 return Double.NaN.

If you compare Double.NaN == Double.NaN you will receive false and this is why System.out.println(0.0%0.0==0.0/0.0); prints false.

The question now goes to why does Double.NaN == Double.NaN return false?

According to JLS:

Floating-point operators produce no exceptions (ยง11). An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false and any != comparison involving NaN returns true, including x!=x when x is NaN.

More info:

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • Interstingly, the byte code is : 0: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; **3: iconst_1** 4: invokevirtual #22; //Method java/io/PrintStream.println:(Z)V 7: getstatic #16; //Field java/lang/System.out:Ljava/io/PrintStream; **10: iconst_0** 11: invokevirtual #22; //Method java/io/PrintStream.println:(Z)V 14: return ... I don't understand why `0` and `1` are being loaded onto the stack here . โ€“ TheLostMind Oct 17 '14 at 07:10