This week's book giveaway is in the Design forum. We're giving away four copies of Building Microservices and have Sam Newman on-line! See this thread for details.

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?

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.

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