aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assigning Values to Primitive Types Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assigning Values to Primitive Types " Watch "Assigning Values to Primitive Types " New topic
Author

Assigning Values to Primitive Types

Michael Scott
Ranch Hand

Joined: Jan 20, 2003
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

Joined: Jan 06, 2003
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


SCJP-1.4; SCWCD-EE5<br />---------<br />Sky is not the limit......
John Paverd
Ranch Hand

Joined: Nov 17, 2002
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.


SCJP 1.4
Tausif Khanooni
Ranch Hand

Joined: Nov 14, 2002
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.


"Walking on water and building IT Architecture from <br />specification are easy if and only if both are frozen"
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Assigning Values to Primitive Types