This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
1. Short v5 = 4; //Legal
2. Integer v6 = 4; //Legal
3. Long v7 = 4; //Illegal
I thought 1st statement (Short v5 = 4;) was illegal since integer literal can't assign to Short. But this statement compiled successfully .
Similarly i thought 3rd statement (Long v7 = 4;) was legal since integer literal can assign to Long. But we are getting the compilation error for this statement.
Can you please clarify me?
Preparing for SCJP 6.0
1. This compiles because the literal 4 is in the range of a short so the compiler will interpret 4 literal as of type short with no implicit narrowing required. Then the short will be autoboxed in a Short wrapper class. Note that this works only for literals and constants and as long as the value is in range.
3. This doesn't compile because implicit-widening has to be done to convert an int to a long. Autoboxing won't work because it needs it's corresponding
primitive type. i.e. only a long literal 4L can be autoboxed in a Long.
Salil Vverma wrote:Could you please explain what you mean by implicit widening in this case as integer and float both take 4 byte in java?
The size of the type doesn't determine whether it is considered widening or narrowing. It is the range of the type that does. In this case, the range of a float is greater than the range of an int, hence, it is considered widening.