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

Negative number divide by zero?

Joey Sanchez
Ranch Hand

Joined: Jun 23, 2011
Posts: 88

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

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

Joined: Oct 14, 2005
Posts: 19973

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

Joined: Oct 02, 2003
Posts: 11955

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

Joined: Apr 11, 2011
Posts: 20

Paul Clapham wrote:

above gives an exception offcourse.
But why as OP asks

Please throw some light.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

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.

I agree. Here's the link:
subject: Negative number divide by zero?
It's not a secret anymore!