Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper Assignments from ExamLab

 
krishna Mohan Athota
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:

 
Salil Vverma
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

 
Henry Wong
author
Marshal
Pie
Posts: 21212
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic