views:

180

answers:

4
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?

A: 

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

Carl Smotricz
correct (15 chars)
Fredrik
+13  A: 

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

Ehrann Mehdan
+2  A: 

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.

slappybag
it return true. did you verify?
GK
@gurukulki: He accidently wrote Float x and Double x. It probabl needs to be the primitives to avoid object identity comparison.
Fredrik
Yep Float x = Float.NaN prints true, float x = Float.NaN prints false
Ehrann Mehdan
A: 

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