CalumJEadie
CalumJEadie

Reputation: 189

Is it possible for a==a to evaluate false for some variable a in Java?

I've been posed this slightly obscure but interesting question about the behavoir of Java. Any ideas?

Upvotes: 2

Views: 164

Answers (4)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

Yes, for float or double NaNs (but not Float or Double). Section 4.2.3 of the JLS 3rd Ed. I believe IEEE 754 defines the operation that way. Those are the only cases.

Upvotes: 6

Peter Lawrey
Peter Lawrey

Reputation: 533500

The code for Double.isNaN()

static public boolean isNaN(double v) {
    return (v != v);
}

This sounds like an interview questions. A similar questions when is x == x + 0 false which has more answers. ;)

Upvotes: 1

developmentalinsanity
developmentalinsanity

Reputation: 6229

As giddy said, concurrency can mess it up. I just tried this:

public class Madness {

    private static volatile long a = 0;

    public static void main(String[] args) {

        long good = 0;
        long bad = 0;

        new Thread() {
            {
                setDaemon(true);
            }

            public void run() {
                while (true)
                    a++;
            }
        }.start();

        long print = System.currentTimeMillis() + 1000;

        while (true) {
            if (a == a)
                good++;
            else
                bad++;
            if (System.currentTimeMillis() > print) {
                System.out.println(String.format("%d / %d", good, bad));
                print = System.currentTimeMillis() + 1000;
            }
        }

    }

}

Output was:

19936409 / 382
38360780 / 640
56895813 / 898
75827635 / 1159
94500958 / 1423
113184503 / 1701
131711068 / 1960
150423573 / 2239
168898106 / 2509

Admittedly, this is a case specifically designed to cause this. Removing the volatile on a changes things. I see some initial "bad" hits, but then it seems to be all good. I haven't investigated, but I have a feeling it's something to do with hot spot optimizing the code after some number of iterations.

Upvotes: 1

st0le
st0le

Reputation: 33545

Yep, Try this...

public class Main
{
  public static void main(String[] args)
  {
    double a = Double.NaN;
    if( a == a ) System.out.println("equal");
  }
}

http://www.ideone.com/K0d2j

Upvotes: 7

Related Questions