my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Negative number divide by zero? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Negative number divide by zero?" Watch "Negative number divide by zero?" New topic
Author

Negative number divide by zero?

Joey Sanchez
Ranch Hand

Joined: Jun 23, 2011
Posts: 86



The result of this code is InfinityException in thread "main" java.lang.ArithmeticException: / by zero at MyClass.main(Test.java)

Why doesn't throw the exception x? Is it because the negative number?
Because is an int, not a double?
Paul Clapham
Sheriff

Joined: Oct 14, 2005
Posts: 19728
    
  10

The little test you can do to answer that question is this:
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11858
    
  18

as Paul pointed out, your test cases are not equivalent. in one, you have a positive number with a decimal point. in the other, you have a negative number without.

having multiple variables (sign of the number, floating point vs integer literals) change across a single test is not a good plan.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
John Call
Greenhorn

Joined: Apr 11, 2011
Posts: 20

Paul Clapham wrote:

Hi,
above gives an exception offcourse.
But why as OP asks

Please throw some light.
Thanks.
Paul Clapham
Sheriff

Joined: Oct 14, 2005
Posts: 19728
    
  10

The code speaks for itself, doesn't it? Dividing an integer by zero throws an exception, dividing a double by zero returns infinity.
John Stark
Ranch Hand

Joined: Jul 19, 2011
Posts: 185
The documentation of the ArithmeticException class says:

Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.




gives an Exception.



gives infinity. The int '1' is treated as a double because '0.' is a double.

John
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Negative number divide by zero?
 
It's not a secret anymore!