wood burning stoves*
The moose likes Beginning Java and the fly likes variable declaration changes output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "variable declaration changes output" Watch "variable declaration changes output" New topic
Author

variable declaration changes output

Daniel .J.Hyslop
Ranch Hand

Joined: May 23, 2005
Posts: 55
in the program below I have initialised two variables with int values and decrement the variable f by one each repetition f eventually becomes 0 which creates a ArithmeticException and I get the desired result for the exercise the code is below

the resultant output is
120/5 is 24
120/4 is 30
120/3 is 40
120/2 is 60
120/1 is 120
cannot devide by zero ---which is what I expectd

I changed the variable f to a double :-

and got this
120/5.0 is 24.0 etc.....
120/1.0 is 120.0
120/0.0 is infinity

Would someone be kind enough to tell me what causes the difference in output when a varialbles initialiser is changed , please


an island in the sun <br />with a language of many tongue?
M. Gagnon
Ranch Hand

Joined: Feb 18, 2004
Posts: 68
Originally posted by daniel hyslop:

120/0.0 is infinity

Would someone be kind enough to tell me what causes the difference in output when a varialbles initialiser is changed , please


According to Horstman and Cornell in "Core Java", that is the normal behavior for types float and double:

". . . the result of dividing a positive number by 0 is positive infinity."

I think it's probably because floating point numbers always have a limited precision.
Philip Heller
author
Ranch Hand

Joined: Oct 24, 2000
Posts: 119
You only get ArithmeticException when you divide an integer by integer zero.


Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by M. Gagnon:
I think it's probably because floating point numbers always have a limited precision.


It's actually part of the IEEE Standard 754 for floating point numbers.

http://stevehollasch.com/cgindex/coding/ieeefloat.html

Being able to denote infinity as a specific value is useful because it allows operations to continue past overflow situations. Operations with infinite values are well defined in IEEE floating point.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: variable declaration changes output