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

Ashish Soni

Greenhorn

Posts: 24

posted 7 years ago

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

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

posted 7 years ago

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

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

Ralph Jaus

Ranch Hand

Posts: 342

Madhukar Ojha

Ranch Hand

Posts: 71

posted 7 years ago

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.

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.

SCJP 5 ๑۩۞۩๑♥~~ My Life is My Creation ~~♥๑۩۞۩๑

posted 7 years ago

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

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

SCJP 5. OCPJWCD 6.

[url] http://passingscjp.blogspot.com [/url]