What makes the following code print false?
public class Gues开发者_开发问答s {
public static void main(String[] args){
<sometype> x = <somevalue>;
System.out.println(x == x);
}
}
i have to change sometype and somevalue so that it returns false? is it possible?
One:
float x = Float.NaN;
Two:
double x = 0.0/0.0;
Why?
As mentioned here already, NaN
is never equal to another NaN
- see http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
So why this is not returning false?
Float x = Float.NaN;
The answer is that here, instead of a primitive assignment, there is a reference assignment. And there is a little auto boxing in the background. This is equal to:
Float x = new Float(Float.NaN);
Which is equal to:
Float x = new Float(0.0f / 0.0f);
Here x is a reference to a Float object, and the == operator tests reference equality, not value.
To see this returning false as well, the test should have been:
x.doubleValue()==x.doubleValue();
Which indeed returns false
Yes it is possible, you need to use:
// Edited for primitives :)
float x = Float.NaN;
// or
double x = Double.NaN;
This is because NaN is a special case that is not equal to itself.
From the JLS (4.2.3):
NaN is unordered, so the numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1). The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x is NaN, and (x=y) will be false if x or y is NaN.
I can't think of any someType
and someValue
for which you could get x == x
to come up false, sorry.
Update
Oh... yes, I think NAN is equal to nothing, even itself. So...
double
and Double.NaN
(or so).
This will print false:
!(x == x)
Other then that, it will only print false if you use NaN
float x = float.NaN;
Console.WriteLine(x == x);
精彩评论