Hi All -- I'm using the "Complete Java 2 Certification Study Guide", 3rd ed., by Phillip Heller and Simon Roberts, Sybex 2002. In the preparation exam for J2 Programmer, the first question is as follows:
-- In the following code fragment, what are the legal data types for the variable, answer? (Choose all that apply)
byte b = 1; char c = 2; short s = 3; int i = 4; float f= = 5f; answer = b*c*s*i*f;
A. byte B. char C. short D. int E. float F. double G. long
The correct choices are E,F. Why is G not correct? Thanks for the advice. [ March 10, 2005: Message edited by: Elaine Ware ]
For binary operands, the operators are widened to the largest type of the operators, and to integers if both operators are of a type smaller than int.
The order is:
byte -> short - |-> int -> long -> float -> double char -
The largest operator in b*c*s*i*f is of type float, so the result is also of type float.
Assignment to a smaller type needs a cast (with the exception of the byte/shot/char assignments with a fitting constant value). Assignment to a wider type is automatic.
So the only valid types of the answer variable are types that are at least as wide as float. Long is smaller than float, so it is not valid.
Joined: Mar 10, 2005
Thanks all for responding. Then is the study guide incorrect? It says that long is 64 bits, while float is 32. Is that correct? [ March 10, 2005: Message edited by: Elaine Ware ]
Joined: Feb 24, 2005
Indeed, long is 64 bits, float 32. BUT widening/narrowing is not only about the number of bits. It is about if you can lose information when converting. And when you convert from a floating type value (float or double) to an integer type, the decimals get cut off - loss of info.
Look at the list of types below. All conversions along the arrows from left to right are defined as widening conversions. All other conversions between non-equal types are narrowing conversions and require a cast.
This is the list you should learn/use for determining if casts are needed, not the actual size in bits of the types.
Note: the following requires a cast, even though char has more bits than byte.
It's not about the number of bits, or about possible loss of precision. It's all about the possible range of values that can be stored.
Even though float is only 32 bit and long is 64 bit float is capable of holding a wider range of values. It is possible to lose precision when putting the value of a long into a float, but the conversion is allowed without a cast.
A long has the range of: -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
while a float has the range of: 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).
So the float is 'wider' than the long.
Joined: Mar 10, 2005
Thanks, everyone. I am very clear on this topic. I didn't memorize the 'widening conversion' chart past int.