This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
By default 100.25 is taken as a double. To assign 100.25 to a float we have to add an extra f or cast it to a float.
The floating point types (float and double) can also be expressed using E or e (for scientific notation), F or f (32-bit float literal) and D or d (64-bit double literal; this is the default and by convention is omitted).
Hope i'm able to make some sense,
Joined: Aug 17, 2007
Still I am not clear.
My question is,
byte b = 100 works fine.
* 100 is an integer literal. It fits within byte range. * So compiler automatically cast here.
float f = 100.25;
* 100.25 is a double literal. It fits within float range. * So Why compiler doesn't cast automatically?
I think, in case of integers, range has to do with the maximum and minimum allowed values. And when within range, no explicit casting is required. Unlike this, in float and double have more to do with "precision" i.e. how many places afterr decimal can it represent. See below an extract from the Java Spec:
The floating-point types are float and double, which are conceptually associated with the single-precision 32-bit and double-precision 64-bit format IEEE 754 values and operations as specified in IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Standard 754-1985 (IEEE, New York).
You might want to look here. Hence I think we cannot conceptualy equate the case of an "in-range" integer assignment to a byte and a double assignment to a float. [ August 23, 2007: Message edited by: Satya Maheshwari ]