I think it should be:
Long a = Long.valueOf(0);
Long b = Long.valueOf(1);
Long a = b.clone();
But there is no clone
method in Long
object...
Maybe Long a = Long.valueOf(b.LongValue())
will work, but it looks dirty. Is there any nice way to handle this?
I think, because Long is immutable, you can just use an assignment.
Long a = (long) 1;
Long b = a;
a = (long) 2;
System.out.printf("a=%d, b=%d%n", a, b);
Output is
a=2, b=1
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With