Win a copy of Design for the Mind this week in the Design forum!

# if(0.0 == -0.0) - Sample question

Ashish Soni
Greenhorn
Posts: 24
All ,

I found a code mentioned below (http://www.examsguide.com/scjp/freequestions8.html)

if(0.0 == -0.0) {
System.out.println("true");
}
else{
System.out.println("false");
}

this prints true and my understanding is that 0 is neither negative nor positive.

Is there is any other reason also , Pleae explain.

Ashish

vaibhav mishra
Ranch Hand
Posts: 168
what you understand explains the simple result
it is true because sign doesn't matter here

both sides of operator are equal and hence true is returned

Henry Wong
author
Marshal
Posts: 20997
76
this prints true and my understanding is that 0 is neither negative nor positive.

This is not completely true. The IEEE floating point spec defines a positive zero and a negative zero. So, a zero can be positive or negative.

They are equal because the specification defines that a positive zero is equal to a negative zero.

But you can tell them apart... For example, the inverse of positive zero is infinity, while the inverse of negative zero is negative infinity.

Henry

Henry Wong
author
Marshal
Posts: 20997
76
For an example of this, take a look at this code...

As you can see, the negative sign attached to the zero is preserved, as the two answers are different.

Henry

Ralph Jaus
Ranch Hand
Posts: 342
But note that corresponding wrappers are not equal:

will print false false.

Ranch Hand
Posts: 71
Hi Ashish

This is one of two special cases .

+0.0 = -0.0 is true
Float.Nan = Float.Nan is false

It is specified in Java API.

Saurabh Patil
Ranch Hand
Posts: 48
Originally posted by Henry Wong:
For an example of this, take a look at this code...

As you can see, the negative sign attached to the zero is preserved, as the two answers are different.

Henry

Hi henry,

I coded that part with some of my own, and I got exiting results. My program was:

The result printed was:
0
0
0
0
Infinity
-Infinity

Can anyone explain me why the 2nd and 4th zero was printed??

Regards,
Saurabh

Henry Wong
author
Marshal
Posts: 20997
76
Can anyone explain me why the 2nd and 4th zero was printed??

The rules discussed in this topic applies to floating point numbers. Your example uses integers.

Henry
[ July 06, 2008: Message edited by: Henry Wong ]