aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding division by zero Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding division by zero" Watch "Regarding division by zero" New topic
Author

Regarding division by zero

palla sridhar
Ranch Hand

Joined: Oct 15, 2007
Posts: 111
Hi Ranchers!
Please look at the code below.
This prints "Infinity" compiled and executed.
Q1. How does it print "Infinity" ?
But when i code like this
and compile,execute,it gives "Arithmetic Exception,
Q2. Why so?

Please help??


Thanks and Regards,
[url]www.techlikes.com[/url]
*Nothing is CONSTANT in life, except CHANGE*
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 417
    
    2

In the first case you current salary is a double initialised with a promoted int, dividing a double by int 0 promotes 0 to double so you are diving two doubles , dividing by zero when in double land ;-) gives Double.Infinity.

Second case you are diving two integers the result of which will be promoted to a double but before that happens the division of two integers occurs ... the result in integer land of division by 0 is an ArithmeticException :-)


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Arvind Mahendra
Ranch Hand

Joined: Jul 14, 2007
Posts: 1162
Originally posted by palla sridhar:
Hi Ranchers!
Please look at the code below.
This prints "Infinity" compiled and executed.
Q1. How does it print "Infinity" ?
But when i code like this
and compile,execute,it gives "Arithmetic Exception,
Q2. Why so?

Please help??


I think this had something to do with the fact that floats/ doubles unlike integeres had 3 parts. : the sign, the mantissa(part of the floating point that contains the significant digits) and the exponent. Internally because we now have an extra part ie:the exponent part you have extra space to represent certain special things within the cpu when you omit an exponent in your representation. So it can use that space to give out values like "infinite". ints dont have that extra space so they choke when faced with a divide by zero and have to throw an exception.
note; i think this may also have to change from CPU to CPU. maybe somone with a mac computer could confirm because its not just divide by zero that can represent "infinities" but other values as well. it may be that some give Nan(when a result of a calculation doesn't really exists like Math.sqrt(-1) for example
[ October 21, 2007: Message edited by: Chunnard Singh II ]

I want to be like marc
 
Don't get me started about those stupid light bulbs.
 
subject: Regarding division by zero