| Author |
Wrapper Assignments from ExamLab
|
krishna Mohan Athota
Greenhorn
Joined: Jul 18, 2009
Posts: 10
|
|
Hi
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
|
 |
Guillaume Jeudy
Greenhorn
Joined: Jul 27, 2009
Posts: 24
|
|
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.
Here are a few samples to demonstrate:
|
SCJP 1.4 and 6.0, SCJD
|
 |
Salil Vverma
Ranch Hand
Joined: Sep 06, 2009
Posts: 219
|
|
Hey Guillaume,
Float f = 4; // illegal implicit widening make autoboxing fail
Could you please explain what you mean by implicit widening in this case as integer and float both take 4 byte in java?
|
Regards
Salil Verma
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16815
|
|
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.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
 |
|
|
subject: Wrapper Assignments from ExamLab
|
|
|