programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Since when does 25/4 = 6.0?

Ranch Hand
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?

Marshal
Posts: 57437
175
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) . . .

Sheriff
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.

Jake Miller
Ranch Hand
Posts: 43
Sweet, got it. Thanks

 Do not set lab on fire. Or this tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS