Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

# Assigning Values to Primitive Types

Michael Scott
Ranch Hand
Posts: 57
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

Vikram Reddy
Greenhorn
Posts: 17
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

John Paverd
Ranch Hand
Posts: 115
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.

Tausif Khanooni
Ranch Hand
Posts: 107
Hi John,
The last statement i.e. <b>f = 1.0 / 3;</b>
will not compile. We need to cast "1.0" to float.