Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am a bit confused with something, perhaps somebody is able to explain it; in the following 3 commands ...

Java
double z1 = (double) ( 12 / 5 );
System.out.println( z1 ); // = 2.0


Java
double z2 = 12 / 5;
System.out.println( z2 ); // = 2.0


Java
double z3 = (double) 12 / 5 ;
System.out.println( z3 ); // = 2.4


... only the third one seems to do the correct calculation.

If a variable is defined as a Double, are you not telling the system that it is a numeric variable with decimal places ? If so, why do the first 2 statements give an incorrect result ?!?
Posted

1 solution

The answer is simple. In the first two cases, the expression 12 / 5 is treated as integer division, as that is the "minimum necessary" to calculate it. Subsequent conversion of the result to double doesn't affect how it was evaluated.
In you third case, you are asking to divide (double) 12 by (integer) 5, so the division has to be 12.0 / 5.0 after the 5 is promoted to double.

Look at any tutorial about expression evaluation (it doesn't even have to be for Java - almost all modern procedural languages that bear any relationship to C use essentially the same rules).

Peter
 
Share this answer
 
Comments
ridoy 7-Sep-12 2:08am    
correct..+5
Gary Heath 7-Sep-12 2:33am    
Thank you Peter, but what I really don't understand is the fact that z1 & z2 are both defined as being Double variables, so *why* does it do Integer division ?!?

Your answer makes perfect sense, but what is the point of being able to define an integer as Double, i.e. it WILL have decimal places, if the calculations to put a value into that variable totally ignore that fact ?!?!?
Peter_in_2780 7-Sep-12 2:46am    
double a = 12; is simply a way of saying double a = 12.0; or double a = (double)12; In any of these cases the value is a double. But the *expression* 12/5 is an integer. The language will always use the "smallest"/"simplest" numeric type that accomodates both operands, which in this case is integer. In your third example, you force the 12 to double, so it must use double arithmetic for the division. As I said before, read up on arithmetic expression evaluation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900