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

Number Wrapper classes - autoboxing

 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Does the constructor of Integer class get called, when I execute above line of code?
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. The method Integer.valueOf(int i) is called.
 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My actual confusion is why doesn't below code compile?


where as this compiles?


 
Rob Spoor
Sheriff
Pie
Posts: 20555
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Auto-boxing only works on literals and variables of the same type. In your second example, you use an explicit method call and the short is widened to an int.
 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Prime wrote:Auto-boxing only works on literals and variables of the same type.


Thank You, I will keep this in mind.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a must read about autoboxing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic