A mock exam has the following question: Which of the following are legal statements? 1) float f=1/3; 2) int i=1/3; 3) float f=1.01; 4) double d=999d; The correct answers are (1), (2) and (4). I don't understand however why (1) and (2) are correct as 1/3 is the same as .3333333... which by default is a double. Assigning a double to either a float variable or an int variable requires casting. Could someone please tell me why (1) and (2) are therefore correct answers. Thanks very much. Michael
Michael, Division of two integer values returns an integer rounded towards 0. (JLS 15.17.2 Division Operator /) The result of 1/3 = 0 and not 0.333 in this context, this explains why '1' and '2' are correct. -- Vikram
SCJP-1.4; SCWCD-EE5<br />---------<br />Sky is not the limit......
float f = 1/3; The type of an expression is determined by the types of its operands. In the expression 1 / 3, both operands are ints, so integer division is used, and the resulting value is an int, 0. On assignment, the int 0 will be promoted to the type of the assigned variable, which is float. Therefore f == 0.0f. Here are some different scenarios to help reinforce the concept: float f; f = 1f / 3; f = (float)1 / 3; f = (float) ( 1 / 3); f = 1.0 / 3; Not all of them will compile.