| Author |
if(0.0 == -0.0) - Sample question
|
Ashish Soni
Greenhorn
Joined: May 25, 2008
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
Joined: Jun 18, 2008
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
|
SCJP
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
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
Joined: Apr 27, 2008
Posts: 342
|
|
But note that corresponding wrappers are not equal: will print false false.
|
SCJP 5 (98%) - SCBCD 5 (98%)
|
 |
Madhukar Ojha
Ranch Hand
Joined: Mar 21, 2007
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.
|
SCJP 5 ๑۩۞۩๑♥~~ My Life is My Creation ~~♥๑۩۞۩๑
|
 |
Saurabh Patil
Ranch Hand
Joined: Dec 11, 2005
Posts: 45
|
|
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
|
All for one and one for all!
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16680
|
|
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 ]
|
 |
 |
|
|
subject: if(0.0 == -0.0) - Sample question
|
|
|