This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Can anybody tell me why(the reason) C is right for following question? The following code will print 1: Double a = new Double(Double.NaN); 2: Double b = new Double(Double.NaN); 3: 4: if( Double.NaN == Double.NaN ) 5: System.out.println("True"); 6: else 7: System.out.println("False"); 8: 9: if( a.equals(b) ) 10: System.out.println("True"); 11: else 12: System.out.println("False"); A) True True B) True False C) False True D) False False Jenny
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12269
1
posted
0
Ewww that is tricky! We know that Double.NaN == Double.NaN as a comparison of double values returns false, so naturally we expect the equals method to fail too. Unfortunately, the Double equals method is: public boolean equals(Object obj) { return (obj != null) && (obj instanceof Double) && (doubleToLongBits(((Double)obj).value) == doubleToLongBits(value)); } which instead of comparing double == double uses the doubleToLongBits conversion so the == ends up comparing the bit patterns - which are equal. This unexpected result IS cited in the Javadocs. Bill