It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrapper Assignments from ExamLab Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper Assignments from ExamLab " Watch "Wrapper Assignments from ExamLab " New topic

Wrapper Assignments from ExamLab

krishna Mohan Athota

Joined: Jul 18, 2009
Posts: 10

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

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: 255

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?

Salil Verma
Henry Wong

Joined: Sep 28, 2004
Posts: 20535

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
I agree. Here's the link:
subject: Wrapper Assignments from ExamLab
It's not a secret anymore!