Something that looks much cleaner in my opinion:
Long a = b.LongValue()
There will be an implicit casting to the boxed value. The b.LongValue()
will return the primitive long and it will automatically be boxed into an object of type Long
.
You can read about boxing and auto-boxing in this link for more information.
Here's the section that talks about autoboxing of primitives:
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Here is the simplest example of autoboxing:
Character ch = 'a';
Just for the completeness of the question:
Boxing - The process of taking a primitive and use it in it's wrapper class. Meaning boxing long
in Long
or int
in Integer
, etc... You can get a boxed value either by creating a new object of the wrapper class as follows:
Long boxed = new Long(1);
Or by assigning a primitive to a variable of type of a wrapper class (auto-boxing):
Long boxed = 1l;
Unboxing - The opposite process of boxing. That's the process of taking a boxed parameter and get its primitive. Either by getValue()
or by auto-unboxing as follows:
Long boxed = new Long(1);
long unboxed = boxed.getValue();
Or by just assigning a boxed object to a primitive:
long unboxed = new Long(1);