File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Since when does 25/4 = 6.0? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Since when does 25/4 = 6.0?" Watch "Since when does 25/4 = 6.0?" New topic
Author

Since when does 25/4 = 6.0?

Jake Miller
Ranch Hand

Joined: Jun 27, 2007
Posts: 43
I am following a book about teaching myself Java, and have this as an exercise:
Create an array to store five objects that are of class Integer, String, Boolean, Character, and Double. Displaye the elements.
Here is my program:



And here is the output:

7
Hello world!
false
x
6.0

How do I get the correct answer for the last element of the array?? I thought making it a double would make it an exact answer, i.e. 6.25 but all I can get as an output is 6.0. What's going on?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40027
    
  28
No, 25 / 4 has always made six. All you are getting from the double is adding a decimal point.


Go and find a table of precedences, and if you are lucky you will have this as the top row:

() . []

for round brackets (parentheses) dot for member access and square brackets for array access.
So, whatever is in the () brackets is executed and completed first. What you have in there is the integer division expression 25 / 4. You already know that integer division loses fractions, so you get 6. When you create a Double object from 6, it can't put the 0.25 bit back, because it has disappeared into cyber-limbo, but there is a 1 somewhere (also in cyber-limbo) which represents the remainder of the division, ie 6 % 4.

Try this little alteration:-

new Double(25.0 / 4) . . .
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

The arithmetic is performed using int literals 25/4. Since int division always truncates, the result is 6, and this is the value that's widended to a double, 6.0.

To perform the arithmetic as doubles, replace one (or both) of the int literals with a double. For example, 25d/4.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jake Miller
Ranch Hand

Joined: Jun 27, 2007
Posts: 43
Sweet, got it. Thanks
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Since when does 25/4 = 6.0?