could somebody please explain me the diff between arithmetic promotion and implicit casting (in terms of numeric data types)?? what are the rules and in what conditions do these two things applied? thank you
arithmetic promotion: compiler promotes the numeric types automatically when ever required to complete an operation. float f=20; compiles fine because the literal 20 is promoted to a float BEACUSE IT CAN BE CONVERTED INTO A FLOAT. this is also known as imlicit casting. specifically: arithmetic promo is implicit up casting b += 2 ==> b=b+2 JLS says it is actually b=(byte)(b+2) - another example of implicit casting this is proved by the fact that b=b+2 will fail to compile....since 2 is an integer type arithmetic promotion and implicit casting are essentially the same things when applied to numeric types
hi all, but looking at this snippet byte b=(int)16.2; byte b1=(short)16.2; byte b2=(char)16.2; what can be inferred ?? is it first explicit casting and then implicit downcasting ??? i'm confused when it will work and when not?? here is something that i found relevant 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.). need more info
byte b=(int)16.2; byte b1=(short)16.2; byte b2=(char)16.2; Here's what I think is happening. The first line is treated the same as if you had put: byte b1 = 16; The 16 is a literal int but will be implicitly cast to a byte if it is within range. So, it works. The other lines won't work because they are not int literals, they have been casted to short and char. These do not allow implicit casting even if the value is within range.
Did you ever grow anything in the garden of your mind? - Fred Rogers. Tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth