I\'m using eclipse java ee to perform java programming.
I had the following line of code in one of my functions:
Long result = -1;
To specify a constant of type long
, suffix it with an L
:
Long result = -1L;
Without the L
, the interpreter types the constant number as an int
, which is not the same type as a long
.
Long result = -1L;
Long result = -1L;
Long result = (long) -1;
Long result
= Long.valueOf(-1); // this is what auto-boxing does under the hood
How it happened in the first place is that the literal -1
is an int
. As of Java5, you can have it auto-boxed into an Integer
, when you use it as on Object
, but it will not be turned into a Long
(only long
s are).
Note that an int is automatically widened into a long when needed:
long result = -1; // this is okay
The opposite way needs an explicit cast:
int number = (int) result;
-1
is a primitive int value, Long
however is the wrapper class java.lang.Long. An primitive integer value cannot be assigned to an Long object. There are two ways to solve this.
Change the type to long
If you change the type from the wrapper class Long
to the primitive type long
java automatically casts the integer value to a long value.
long result = -1;
Change the int value to long
If you change the integer value from -1
to -1L
to explicit change it to an long literal java can use this primitive value to automatically wrap this value to an java.lang.Long
object.
Long result = -1L;
There is no conversion between the object Long
and int
so you need to make it from long
. Adding a L
makes the integer -1
into a long
(-1L
):
Long result = -1L;
However there is a conversion from int
a long
so this works:
long result = -1;
Therefore you can write like this aswell:
Long result = (long) -1;
Converting from a primitive (int
, long
etc) to a Wrapper object (Integer
, Long
etc) is called autoboxing, read more here.
-1
can be auto-boxed to an Integer.
Thus:
Integer result = -1;
works and is equivalent to:
Integer result = Integer.valueOf(-1);
However, an Integer can't be assigned to a Long, so the overall conversion in the question fails.
Long result = Integer.valueOf(-1);
won't work either.
If you do:
Long result = -1L;
it's equivalent (again because of auto-boxing) to:
Long result = Long.valueOf(-1L);
Note that the L
makes it a long
literal.