What makes the following code print false?

倾然丶 夕夏残阳落幕 提交于 2019-12-22 11:26:16

问题


public class Guess {
    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?


回答1:


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




回答2:


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.




回答3:


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).




回答4:


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);


来源:https://stackoverflow.com/questions/2012354/what-makes-the-following-code-print-false

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!