Working with Java Wrappers by Example

There are two ways to convert a Java primitive into an object:
1. Using a constructor.
2. Using a static factory method.

Using a Constructor

Integer numericalValue = new Integer(10); 
#> 10 

What’s happening here? Surprisingly, the value of “10” that’s passed into a new Integer is a primitive int. This primitive int is autoboxed as a Integer to properly initialize an Integer class.

Using a Static Factory Method

Integer bestNumberEver = Integer.valueOf(8);
#> 8 

What’s happening here? Java is autoboxing the value of 8 by creating an instance of its primitive value into a Integer value. In fact, so much of this is auto-magic with Java now, that you could simply establish the variable as:

Integer bestNumberEver = 8; 
#> 8

What curiosities do you hold about Java objects or primitives? Comment below and we can discuss them further!

Be the first to reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.