I get compile errors on two of the statements: byte c = short(16.2) Incompatible type for declaration. Explicit cast needed to convert short to byte. byte c = char(16.2) Incompatible type for declaration. Explicit cast needed to convert char to byte. On the other hand, these definitions compile without problem: byte a=(int)16.2; short b = (short)16.2; char c=(char)16.2; Was the question about the explicit cast of 16.2 to an int, a short, and a char? Or was it about the implicit cast of short to byte and char to byte?
hi all, none of the original three statements is giving a compiler error .if u print them all gives 16.i hope what rajshree said regarding byte c=(int)16.2; applies to others as well. please correct
posted 18 years ago
i too am getting compile error for 2nd and 3rd statements saying explicit casting needed as Jo Oehrlein has written.i think if an integer literal is within the range of a data type(byte,short or int)implicit casting takes place.however,if a short or char is to be converted into byte explicit casting is neccessary.
I ran the three statements and they compile and run fine. According to R & H, the reason that they compile is that the right hand value is implicitly downcasted to the appropiate type before assignment. R & H says this only works for integral types (char, byte, short, int) and that it only works if it is just an assignment not an expression. (page 65, 2nd ed.). For example: <pre> byte x = 2; // Legal implicitly casts 2 to byte byte x = (char)2; // same thing
x += (char)5; // Legal x now equals 7
x = x + (char)5; // Illegal, the right hand // operands are promoted to // int before being added // and assigned. Requires // explicit cast to byte </pre> Sorry if this was confusing, but check out page 65 in the R & H book for details. (prob different page in an older addition, it is the section on assignment Operators in he Operators and Assignments chapter).
[This message has been edited by scott nichols (edited March 31, 2001).]
I yam what I yam and that's all that I yam - the great philosopher Popeye. Tiny ad:
Create Edit Print & Convert PDF Using Free API with Java