programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# Assigning Values to Primitive Types

Ranch Hand
Posts: 57
• Number of slices to send:
Optional 'thank-you' note:
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

Greenhorn
Posts: 17
• Number of slices to send:
Optional 'thank-you' note:
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

Ranch Hand
Posts: 115
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 107
• Number of slices to send:
Optional 'thank-you' note:
Hi John,
The last statement i.e. <b>f = 1.0 / 3;</b>
will not compile. We need to cast "1.0" to float.

 Don't get me started about those stupid light bulbs.